@Autowired和PropertyPlaceholder

woe*_*ann 5 java spring

是否可以通过@Autowired将PropertyPlaceholder中的属性添加到bean中?我无法在xml-context-config中注入它,因为bean以这种方式加载:

<context:component-scan base-package="..."/>
Run Code Online (Sandbox Code Playgroud)

sem*_*ral 9

在3.0版本(我认为来自里程碑3),您可以使用@Value("$ {foo.bar}")来访问PropertyPlaceholder中的属性.

  • 是的,假设您有如下配置的属性占位符:`<context:property-placeholder location ="classpath:app.properties"/>`您可以使用来自`app.properties的键'foo.bar`注入属性的值`to you bean:`class MyBean {@Value($ {"foo.bar"} private String value;}` (2认同)

Pau*_*zie 6

春季2.5方法:

@Component
public class Foo {
    @Autowired 
    @Qualifier("myFlag")
    private Boolean flag;
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

和背景

<context:component-scan base-package="..."/>
<context:property-placeholder location="classpath:app.properties"/>
<!-- the flag bean -->
<bean id="myFlag" class="java.lang.Boolean">
    <constructor-arg value="${foo.bar}"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

干杯