2010-01-19 54 views
5

是否可以通過@Autowired將屬性從PropertyPlaceholder添加到bean中?因爲bean被裝載,我不能在XML的上下文配置注入這樣說:@Autowired和PropertyPlaceholder

<context:component-scan base-package="..."/> 

回答

9

春天3.0(我覺得從里程碑3)你可以使用@Value(「$ {foo.bar }「)從PropertyPlaceholder訪問屬性。

+0

你可以給我一個這樣的例子上下文

<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> 

乾杯?我使用spring 3 rc3,當我嘗試這種方式(例如@Value(「$ {foo.bar}」)),那麼我的屬性獲得值「foo.bar」... – woezelmann 2010-01-19 15:08:59

+2

是的,讓我們說你有屬性佔位符配置像這樣: ''' 你可以從'app.properties'向你注入屬性值爲'foo.bar'的bean: 'class MyBean { @ Value($ {「foo.bar」} private String value; }' – semberal 2010-01-19 15:16:03

+0

對不起,格式化,我是新來的:) – semberal 2010-01-19 15:22:17

6

彈簧2.5的方法:

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

+0

+1或者稍微詳細一點,'@Resource(name =「myFlag」)' – skaffman 2010-01-19 16:54:34