弹簧设置库 [英] spring settings repository
问题描述
我的许多应用程序属性由数据库提供,我想通过存储库注入它们。我想知道春天是否可行。如果有人可以提出解决方案,我会很高兴。我正在考虑的代码看起来像这样:
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);
}
}
我知道我可以将PlatformSettingRepositoy注入服务中查找它。但是我不想在调用时进行这些查找,而是希望spring容器在启动时进行查找。
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.
推荐答案
使用Spring表达式语言。
Use Spring expression language.
步骤1:使用@Bean公开您的设置哈希图,用id = appSettings来说
Step 1: Expose your settings hashmap using @Bean, lets say with id ="appSettings"
步骤2:现在您要注入设置1的位置,只需使用批注:
Step 2: Now where you want settings 1 injected, just use the annotation :
@Value("#{ appSettings['setting1'] }")
private PlatformSetting setting1;
注意:这适用于普通值,也适用于您的情况。尽管我还没有尝试过。
如果这不起作用,则可以直接在您的方法中使用表达式解析器,因为您已经在使用java config初始化bean的方式。
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.
这篇关于弹簧设置库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!