spring中使用autowire特性时注意
spring中可以只用autowire="byName"或者"byType"来提供自动注入。但是大家有一点还需要注意,那就是它不支持基本数据类型(String,int,long等)的自动注入。例如
JAVA类:
- public class TestBean {
- private String name;
- private Long age;
- private String fullName;
- private TestBean2 testBean2;
- public void setTestBean2(TestBean2 testBean2) {
- this.testBean2 = testBean2;
- }
- public TestBean2 getTestBean2() {
- return testBean2;
- }
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
- public String getFullName() {
- return fullName;
- }
- public void setAge(Long age) {
- this.age = age;
- }
- public Long getAge() {
- return age;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- }
- public class TestBean2 {
- public String getString(){
- return "testB";
- }
- }
- <beans default-autowire="byName">
- <!-- login -->
- <bean id="testBean" class="TestBean">
- <property name="fullName">
- <value>fullName</value>
- </property>
- </bean>
- <bean id="name" class="java.lang.String">
- <constructor-arg>
- <value>hell</value>
- </constructor-arg>
- </bean>
- <bean id="age" class="java.lang.Long">
- <constructor-arg>
- <value>20</value>
- </constructor-arg>
- </bean>
- <bean id="testBean2" class="TestBean2"/>
- </beans>
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Test {
- public static void main(String[] args) {
- ClassPathXmlApplicationContext t = new ClassPathXmlApplicationContext(
- "test.xml");
- TestBean bean = (TestBean) t.getBean("testBean");
- System.out.println("name:" + bean.getName() + " age:" + bean.getAge()
- + " fullName :" + bean.getFullName() + " testBean2"
- + bean.getTestBean2().getString());
- }
- }
name:null age:null fullName :fullName testBean2:testB
spring源码中排除基本类型的代码(源码来自:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory类)在:
- protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
- Set result = new TreeSet();
- PropertyValues pvs = mbd.getPropertyValues();
- PropertyDescriptor[] pds = bw.getPropertyDescriptors();
- for (int i = 0; i < pds.length; i++) {
- if (pds[i].getWriteMethod() != null && !isExcludedFromDependencyCheck(pds[i]) &&
- !pvs.contains(pds[i].getName()) && !BeanUtils.isSimpleProperty(pds[i].getPropertyType())) {
- result.add(pds[i].getName());
- }
- }
- return StringUtils.toStringArray(result);
- }
请注意以上紫色部分。而这个unsatisfiedNonSimpleProperties方法都是在自动注入时调用。所以基本类型不会被注入。