Reputation: 1901
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 /// what about this one?
}
Upvotes: 6
Views: 7962
Reputation: 291
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;
Upvotes: 2
Reputation: 597134
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;
Upvotes: 5