问题
many of my application-properties are provided by the database i would like to inject them via a repository. I wonder if this is doable with spring. I would be happy if someone could suggest a solution. The code i'm thinking about looks something liek this:
@Component
public class ExampleService implements Service {
private PlatformSetting setting1;
@Required
@Qualifier("setting1")
public void setSetting1(PlatformSetting setting1) {
this.setting1 = setting1;
}
public String getMessage() {
return "Hello world!" + setting1.getValue();
}
}
@Repository
public class PlatformSettingRepository {
private HashMap<String, PlatformSetting> settings;
{
settings = new HashMap<String, PlatformSetting>();
settings.put("setting1", new PlatformSetting("bla1"));
settings.put("setting2", new PlatformSetting("bla2"));
}
@Bean
public PlatformSetting findSetting(@Qualifier String qual) {
return settings.get(qual);
}
}
i know i could just inject the PlatformSettingRepositoy into the service to look it up. But i don't want to make these lookups at invocation time i want the spring container to do them on startup.
回答1:
Use Spring expression language.
Step 1: Expose your settings hashmap using @Bean, lets say with id ="appSettings"
Step 2: Now where you want settings 1 injected, just use the annotation :
@Value("#{ appSettings['setting1'] }")
private PlatformSetting setting1;
Note: This works with plain values, and it should work in your case as well. Though I haven't tried it. If this doesn't work, you could directly use a expression parser in your method since you are already using java config way of initializing beans.
回答2:
PropertyPlaceholderConfigurer combined with CommonsConfigurationFactory is your answer. Please take a look at this post.
回答3:
You can use InitializingBean:
@Component
public class Config implements InitializingBean {
/**
* Used to hold app properties.
*/
private Properties properties = new Properties();
//Getters, setters and filling properties from where you need
public void afterPropertiesSet() throws Exception {
//Initialize some static properties of other objects here.
}
}
than inject Config to your other classes.
来源:https://stackoverflow.com/questions/10805851/spring-settings-repository