spring中使用autowire特性时注意


spring中可以只用autowire="byName"或者"byType"来提供自动注入。但是大家有一点还需要注意,那就是它不支持基本数据类型(String,int,long等)的自动注入。例如
JAVA类:
  1. publicclassTestBean{
  2. privateStringname;
  3. privateLongage;
  4. privateStringfullName;
  5. privateTestBean2testBean2;
  6. publicvoidsetTestBean2(TestBean2testBean2){
  7. this.testBean2=testBean2;
  8. }
  9. publicTestBean2getTestBean2(){
  10. returntestBean2;
  11. }
  12. publicvoidsetFullName(StringfullName){
  13. this.fullName=fullName;
  14. }
  15. publicStringgetFullName(){
  16. returnfullName;
  17. }
  18. publicvoidsetAge(Longage){
  19. this.age=age;
  20. }
  21. publicLonggetAge(){
  22. returnage;
  23. }
  24. publicvoidsetName(Stringname){
  25. this.name=name;
  26. }
  27. publicStringgetName(){
  28. returnname;
  29. }
  30. }
JAVA类2:
  1. publicclassTestBean2{
  2. publicStringgetString(){
  3. return"testB";
  4. }
  5. }
配置文件:
  1. <beansdefault-autowire="byName">
  2. <!--login-->
  3. <beanid="testBean"class="TestBean">
  4. <propertyname="fullName">
  5. <value>fullName</value>
  6. </property>
  7. </bean>
  8. <beanid="name"class="java.lang.String">
  9. <constructor-arg>
  10. <value>hell</value>
  11. </constructor-arg>
  12. </bean>
  13. <beanid="age"class="java.lang.Long">
  14. <constructor-arg>
  15. <value>20</value>
  16. </constructor-arg>
  17. </bean>
  18. <beanid="testBean2"class="TestBean2"/>
  19. </beans>
测试类:
  1. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  2. publicclassTest{
  3. publicstaticvoidmain(String[]args){
  4. ClassPathXmlApplicationContextt=newClassPathXmlApplicationContext(
  5. "test.xml");
  6. TestBeanbean=(TestBean)t.getBean("testBean");
  7. System.out.println("name:"+bean.getName()+"age:"+bean.getAge()
  8. +"fullName:"+bean.getFullName()+"testBean2"
  9. +bean.getTestBean2().getString());
  10. }
  11. }
输出的结果是:
name:null age:null fullName :fullName testBean2:testB


spring源码中排除基本类型的代码(源码来自:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory类)在:
  1. protectedString[]unsatisfiedNonSimpleProperties(AbstractBeanDefinitionmbd,BeanWrapperbw){
  2. Setresult=newTreeSet();
  3. PropertyValuespvs=mbd.getPropertyValues();
  4. PropertyDescriptor[]pds=bw.getPropertyDescriptors();
  5. for(inti=0;i<pds.length;i++){
  6. if(pds[i].getWriteMethod()!=null&&!isExcludedFromDependencyCheck(pds[i])&&
  7. !pvs.contains(pds[i].getName())&&!BeanUtils.isSimpleProperty(pds[i].getPropertyType())){
  8. result.add(pds[i].getName());
  9. }
  10. }
  11. returnStringUtils.toStringArray(result);
  12. }

请注意以上紫色部分。而这个 unsatisfiedNonSimpleProperties方法都是在自动注入时调用。所以基本类型不会被注入。

你可能感兴趣的:(spring,bean,xml)