我在我的应用中使用spring,并且我有一个.prooperties文件,其中定义了一些值。
在java类中有一个String值:
@Value("${test}")
public String value;
关键是如果我在bean定义中注入这个值:
<bean id="customClass" class="package.customClass.CustomClassImpl">
<property name="value" value="${test}"></property>
</bean>
它工作正常,但如果我使用@Value
,则总会有null
...为什么会发生这种情况?
不,我没有做任何&#34; new
&#34;没有intanciate&#34; customClass
&#34;,我用context.getBean("customClass)
得到它。
编辑:我在上下文中配置了一个属性占位符:
<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:constants.properties</value>
</list>
</property>
</bean>
提前致谢。
答案 0 :(得分:3)
请注意,您的课程需要像@Component
或@Service
答案 1 :(得分:2)
如果您正在创建Spring启动应用程序,并且您的目标是通过(应用程序).properties提供配置参数,则可以在没有显式@Value声明的情况下执行此操作。
使用注释创建YourClassProperties @ConfigurationProperties(“some.prefix”):
@ConfigurationProperties("my.example")
public class MyClassProperties {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
将定义的属性添加到(application).properties:
my.example.foo=bar
然后,在您的应用程序中,您可以自动装配所需的属性......
@Autowired
private MyClassProperties myClassProperties;
...并像使用其他任何属性一样使用它们:
LOG.info("Value of the foo: {}", myClassProperties.getFoo());
答案 2 :(得分:0)
您需要使用@PropertySource声明您的.properties文件。不确定它是否可以使用xml config。
另外,你确定这个“$”,在这个例子中它是“#”: http://forum.spring.io/forum/spring-projects/container/61645-value-and-propertyplaceholderconfigurer
答案 3 :(得分:0)
解决,您需要在配置文件中启用注释配置:<context:annotation-config/>