I am using spring 4.0.5 & Java 1.7.0-51. I create a spring bean of type Integer & set the value through it's constructor as follows in Applicationcontext.xml.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<context:component-scan base-package="com.spring.beans"></context:component-scan>
<bean id="user.min" class="java.lang.Integer"> <constructor-arg value="30" /></bean>
<bean id="machine.min" class="java.lang.Integer"> <constructor-arg value="30" /></bean>
</beans>
I inject these beans to my class, where I already set some default values.
@Component
public class Token {
@Autowired(required = false)
@Qualifier("user.min")
private Integer userMin = 480;
@Autowired(required = false)
@Qualifier("machine.min")
private int machineMin = 480;
public Integer getUserMin() {
return userMin;
}
public void setUserMin(Integer userMin) {
this.userMin = userMin;
}
public int getMachineMin() {
return machineMin;
}
public void setMachineMin(int machineMin) {
this.machineMin = machineMin;
}
When I print these values, I get following values.
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("Applicationcontext.xml");
Token t = context.getBean(Token.class);
System.out.println("User:"+t.getUserMin());
System.out.println("Machine:"+t.getMachineMin());
}
Output:
User:30
Machine:480

The value to userMin (class Integer) is injected from bean, but machineMin (primitive type int) value is not injected.
The primitive type 'int' is not Autoboxed to Integer. Is it a bug in Spring or the way I did the configuration is wrong? I am working it on Windows 7 (Eclipse Juno). Someone please help.
The problem is that Spring, with annotation configuration, annotates by type (first and then by name). It looks for a bean of whatever type the field or method (or constructor) parameter is. In your case, that is int and there is no bean of type int in the ApplicationContext. Since your injection target is not required, Spring does not throw an exception.
I wouldn't say this is a bug, there are workarounds, just not with @Autowired.
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