Spring Util:通过注释将属性注入到bean中

Nig*_*olf 30 java spring dependency-injection properties

如果我在Spring XML中设置了2个.properties文件,那么:

<util:properties id="serverProperties" location="file:./applications/MyApplication/server.properties"/>
<util:properties id="someConfig" location="file:./applications/MyApplication/config.properties"/>
Run Code Online (Sandbox Code Playgroud)

如何通过注释将这些属性文件注入到bean中java.util.Properties

如何通过Spring注释获取特定属性?

干杯!

Rya*_*art 46

@Autowired
@Qualifier("serverProperties")
private Properties serverProperties;
@Autowired
@Qualifier("someConfig")
private Properties otherProperties;
Run Code Online (Sandbox Code Playgroud)

要么

@Resource(name = "serverProperties")
private Properties serverProperties;
@Resource(name = "someConfig")
private Properties otherProperties;
Run Code Online (Sandbox Code Playgroud)

通常,@ Autowired用于Spring中的类型自动装配,而@Resource用于按名称.@ Autowired + @ Qualifier可以兼作自动装配,但它真正意味着可以通过微调类型来实现类型自动装配.


Nig*_*olf 16

因为这个问题有很多热门话题.我认为使用SpEL(Spring Expression Language)指出另一个选项是值得的 - 如果你需要特定的属性,可以使用特定bean属性的@Value注释注入它们;

class SomeClass {
   @Value("#{serverProperties['com.svr.prop']}")
   private String aServerCfgProperty;

   @Value("#{someConfig['another.config.setting']}")
   private String someOtherProperty;
}
Run Code Online (Sandbox Code Playgroud)

您不需要使用索引语法,['index.val']您可以直接获取它;

@Value("#{someConfig}")
private Properties someConfig

@Value("#{serverProperties}")
private Properties svrProps;
Run Code Online (Sandbox Code Playgroud)

我发现这很有用,并且不再使用通过@ Resource/@ Autowired直接注入的属性对象.

使用@Value带索引的Properties对象的另一个好理由是,如果项目中的.properties文件也很好,某些IDE(例如IntelliJ)可以重构实际的属性名称.如果你想在属性文件中进行包含/嵌套/替换而不使用Spring的类(遗憾的是它没有公开它的属性 - 使用SpEL索引bean的需要,那么另一个提示是使用像EProperties(扩展本机Java Properties对象)之PropertiesPlaceholderConfigurer类的东西.['key']Map<>Java Properties对象所做的扩展映射的实例...

最后,SpEL的另一个优点是你可以直接访问bean的属性.所以说例如,如果SomeClass在上面的例子中是一个Spring bean,someClass那么在AnotherBeanClass中我们可以拥有;

@Value("#{someClass.someOtherProperty}")
private String injectedBeanProp
Run Code Online (Sandbox Code Playgroud)

你也可以调用一个getter方法:

@Value("#{someClass.getSomeOtherProperty()}")
private String injectedBeanProp
Run Code Online (Sandbox Code Playgroud)

请参阅SpEL指南; http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#expressions