Spring bean primitive properties when using @Component and @Autowired?
How to set value for primitive properties of a bean?
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开发者_StackOverflow /// what about this one?
}
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}")
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>
and then
@Autowired
@Qualifier("foo")
private int foo;
I tried the second approach suggested by Bozho. It seems not working.
The below one is working. Define bean as:
<bean id="foo" class="java.lang.Integer" factory-method="valueOf">
<constructor-arg value="20" />
</bean>
and then
@Autowired
@Qualifier("foo")
private java.lang.Integer foo;
OR
@Autowired
private java.lang.Integer foo;
精彩评论