开发者

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

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开发者_StackOverflow /// 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;


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜