Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean primitive properties when using @Component and @Autowired?

Tags:

java

spring

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?
}
like image 883
Tarun Sapra Avatar asked Mar 29 '11 04:03

Tarun Sapra


1 Answers

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;
like image 108
Bozho Avatar answered Oct 27 '22 00:10

Bozho