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

How to set value for primitive bean properties?

Since we have the annotation @Component , as well as @Autowired , the annotation is also associated with instance binding, so what about primitive properties?

 @Component class Person{ @Autowired Address address; int age /// what about this one? } 
+4
source share
2 answers

For primitives, you can use the @Value annotation. A common scenario is to have a PropertyPlaceholderConfigurer that has loaded values ​​from a properties file and then has @Value("${property.key}")

You can also define your values ​​as beans, which is an older school:

 <bean id="foo" class="java.lang.Integer" factory-method="valueOf"> <constructor-arg value="20" /> </bean> 

and then

 @Autowired @Qualifier("foo") private int foo; 
+4
source

I tried the second approach suggested by Bojo. It doesn't seem to work.

Below is the work. Define a 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; 
+2
source

Source: https://habr.com/ru/post/1345654/


All Articles