使用@Component和@Autowired时的Spring bean基本属性? [英] Spring bean primitive properties when using @Component and @Autowired?
本文介绍了使用@Component和@Autowired时的Spring bean基本属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为bean的原始属性设置值?
How to set value for primitive properties of a bean?
因为我们有@Component
批注,而且@Autowired
批注也用于绑定实例依赖项,所以原始属性呢?
Since we have @Component
annotation and also @Autowired
annotation also is for binding instance dependencies, so what about primitive properties?
@Component
class Person{
@Autowired
Address address;
int age /// what about this one?
}
推荐答案
对于基元,可以使用@Value
批注.通常的情况是让PropertyPlaceholderConfigurer
从属性文件中加载值,然后让@Value("${property.key}")
For primitives you can use the @Value
annotation. The usual scenario is to have a PropertyPlaceholderConfigurer
which has loaded the values from a properties file, and then have @Value("${property.key}")
您还可以将值定义为bean,这是比较古老的:
You can also define your values as beans, which is more old-school:
<bean id="foo" class="java.lang.Integer" factory-method="valueOf">
<constructor-arg value="20" />
</bean>
然后
@Autowired
@Qualifier("foo")
private int foo;
这篇关于使用@Component和@Autowired时的Spring bean基本属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文