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.
PropertyPlaceholderConfigurer combined with CommonsConfigurationFactory is your answer. Please take a look at this post.
You can use InitializingBean:
than inject Config to your other classes.
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 :
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.