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?
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With