简体   繁体   English

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

[英]Spring Util:Properties Injection via Annotations into a bean

If I have 2 .properties files setup in my Spring XML as so: 如果我在Spring XML中设置了2个.properties文件,那么:

<util:properties id="serverProperties" location="file:./applications/MyApplication/server.properties"/>
<util:properties id="someConfig" location="file:./applications/MyApplication/config.properties"/>

How can I inject via annotations these properties files into a bean with java.util.Properties ? 如何通过注释将这些属性文件注入到带有java.util.Properties的bean java.util.Properties

How can I grab specific properties via Spring annotations? 如何通过Spring注释获取特定属性?

Cheers! 干杯!

@Autowired
@Qualifier("serverProperties")
private Properties serverProperties;
@Autowired
@Qualifier("someConfig")
private Properties otherProperties;

or 要么

@Resource(name = "serverProperties")
private Properties serverProperties;
@Resource(name = "someConfig")
private Properties otherProperties;

Typically, @Autowired is used for by-type autowiring in Spring, and @Resource is used for by-name. 通常,@ Autowired用于Spring中的类型自动装配,而@Resource用于按名称。 @Autowired+@Qualifier can double as by-name autowiring, but it's really meant for by-type autowiring with the ability to fine-tune the type . @ Autowired + @ Qualifier可以兼作自动装配,但它真正意味着可以通过微调类型来实现类型自动装配。

As this question has a lot of hits. 因为这个问题有很多热门话题。 I thought it would be worthwhile to point out another option using SpEL (Spring Expression Language) - if you need specific properties they can be injected using the @Value annotation on specific bean properties; 我认为使用SpEL(Spring Expression Language)指出另一个选项是值得的 - 如果你需要特定的属性,可以使用特定bean属性的@Value注释注入它们;

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

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

You dont need to use the indexing syntax ['index.val'] you can just get it directly; 你不需要使用索引语法['index.val']你可以直接得到它;

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

@Value("#{serverProperties}")
private Properties svrProps;

I have found this rather useful and moved away from using the properties object directly injected via @Resource/@Autowired. 我发现这很有用,并且不再使用通过@ Resource / @ Autowired直接注入的属性对象。

Another nice reason for using the @Value with an indexed Properties object is that some IDEs (eg IntelliJ) can refactor the actual property names if you also have the .properties file in the project which is nice. @Value与索引的Properties对象一起使用的另一个好理由是,如果项目中的.properties文件也很好,某些IDE(例如IntelliJ)可以重构实际的属性名称。 Another tip is to use something like EProperties (which extends the native Java Properties object) if you want to do inclusion/nesting/substitution in properties files without using Spring's PropertiesPlaceholderConfigurer class (which sadly doesnt expose its properties - to use SpEL indexing ['key'] the bean needs to be an instance of Map<> ie extend map which the Java Properties object does)... 如果你想在属性文件中进行包含/嵌套/替换而不使用Spring的PropertiesPlaceholderConfigurer类(遗憾的是它没有公开它的属性 - 使用SpEL索引['key'] ],那么另一个提示是使用类似EProperties (扩展本机Java Properties对象)之类的东西。 ['key'] bean需要是Map<>的实例,即Java Properties对象所做的扩展map ...

Finally, another neat feature with SpEL is you can access properties of beans directly. 最后,SpEL的另一个优点是你可以直接访问bean的属性。 So say for example if SomeClass in the example above was a Spring bean eg someClass then in AnotherBeanClass we could have; 所以说,例如,如果上面的例子中的SomeClass是一个Spring bean,例如someClass那么在AnotherBeanClass中我们可以拥有;

@Value("#{someClass.someOtherProperty}")
private String injectedBeanProp

You could also call a getter method: 你也可以调用一个getter方法:

@Value("#{someClass.getSomeOtherProperty()}")
private String injectedBeanProp

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

You can use @PropertySource 您可以使用@PropertySource

@Configuration
@PropertySource(name = "someName", value = {"classpath:a.properties", "classpath:b.properties"})
public class MyConfiguration {
}

XMl file XMl文件

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.0.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 http://www.springframework.org/schema/util 
 http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <context:component-scan base-package="com.sha.home" />
    <mvc:annotation-driven/>
    <util:properties id="dbProp" location="classpath:db.properties" />
    <!-- <context:property-placeholder location="classpath:db.properties"/> -->

</beans>

in java file @Value("#{dbProp}") private Properties dbProperties; 在java文件中@Value(“#{dbProp}”)私有属性dbProperties;

System.out.println("urllll"+dbProperties.getProperty("jdbc.url")); 的System.out.println( “urllll” + dbProperties.getProperty( “jdbc.url”));

Most of time I encapsulate all properties in to a one utility and used in my apps. 大部分时间我将所有属性封装到一个实用程序中并在我的应用程序中使用。 In that way you don't need to worry/manage each properties file in app layer. 这样,您无需担心/管理应用层中的每个属性文件。 Autowired setProps(...) reads all you loaded util:properties in to the props list. 自动装配的setProps(...)将所有加载的util:properties读入到props列表中。

import java.util.List;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AppProperiesProcessor {

private List<Properties> props;
private Properties mergedProperties;

@Autowired
public final void setProps(List<Properties> props) {
    this.props = props;
}

public String getProp(final String keyVal) {

    if (null == this.mergedProperties) {
        this.mergedProperties = new Properties();

        for (Properties prop : this.props) {
            this.mergedProperties.putAll(prop);
        }
    }
    return mergedProperties.getProperty(keyVal);
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM