首页 > 代码库 > Spring系列【10】按照Bean的名称自动装配

Spring系列【10】按照Bean的名称自动装配

User.java

 1 package com.lh.entity; 2  3 public class User { 4            private String name = "test";    //用户姓名 5         private Integer age = 27;            //年龄 6         private String sex = "男";            //性别 7         public String getName() { 8             return name; 9         }10         @Override11         public String toString() {12             return "User [name=" + name + ", age=" + age + ", sex=" + sex + "]";13         }14         public void setName(String name) {15             this.name = name;16         }17         public Integer getAge() {18             return age;19         }20         public void setAge(Integer age) {21             this.age = age;22         }23         public String getSex() {24             return sex;25         }26         public void setSex(String sex) {27             this.sex = sex;28         }29 30 }

PrintInfo.java

 1 package com.lh.util; 2  3 import com.lh.entity.User; 4  5 public class PrintInfo { 6     private String mm="这是什么?"; 7     public String getMm() { 8         return mm; 9     }10 11     public void setMm(String mm) {12         this.mm = mm;13     }14 15     private User user;16     public User getUser() {17         return user;18     }19 20     @Override21     public String toString() {22         return "PrintInfo [mm=" + mm + ", user=" + user + "]";23     }24 25     public void setUser(User user) {26         this.user = user;27     }28     29 }

Spring配置文件

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:context="http://www.springframework.org/schema/context" 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 7  8     <bean id="user" class="com.lh.entity.User"></bean> 9     <bean id="printInfo" class="com.lh.util.PrintInfo"10         autowire="byName">11     </bean>12 </beans>

注意byName和byType的用法,如果有多个User的bean,则byType会出错。

Spring系列【10】按照Bean的名称自动装配