码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-14 23:57:06      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   sp   java   on   

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         @Override
11         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     @Override
21     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的名称自动装配

标签:style   blog   http   io   color   os   sp   java   on   

原文地址:http://www.cnblogs.com/jikoy/p/4163834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!