6

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?
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
Tarun Sapra
  • 1,851
  • 6
  • 26
  • 40

2 Answers2

5

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;
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Second approach seems not to work as you wrote here - http://stackoverflow.com/questions/6291462/inject-primitive-properties-to-spring-bean-when-using-autowired#6292220 – Betlista Aug 29 '13 at 11:37
2

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;
user
  • 291
  • 1
  • 3
  • 16