介绍spring的autowite自动装配
关键代码:
<bean id="user" class="com.shuoeasy.com.test.User" p:id="1001" p:name="说易事"></bean> <!-- 根据属性名和set方法匹配 --> <bean id="order2" class="com.shuoeasy.com.test.Order" p:id="8889" autowire="byName"></bean> <!-- 根据类型匹配,如果发现多个合适的bean匹配会发生异常 --> <bean id="order3" class="com.shuoeasy.com.test.Order" p:id="8890" autowire="byType"></bean>
详细描述:
User.java
package com.shuoeasy.com.test; public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
Order.java
package com.shuoeasy.com.test; public class Order { private int id; private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Order [id=" + id + ", user=" + user + "]"; } }
bean.xml
<?xml version="1.0" encoding="UTF-8"?> <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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="user" class="com.shuoeasy.com.test.User" p:id="1001" p:name="说易事"></bean> <bean id="order1" class="com.shuoeasy.com.test.Order" p:id="8888" p:user-ref="user"></bean> <!-- 根据属性名和set方法匹配 --> <bean id="order2" class="com.shuoeasy.com.test.Order" p:id="8889" autowire="byName"></bean> <!-- 根据类型匹配,如果发现多个合适的bean匹配会发生异常 --> <bean id="order3" class="com.shuoeasy.com.test.Order" p:id="8890" autowire="byType"></bean> </beans>
Main.java
package com.shuoeasy.com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); Order order1 = (Order) ctx.getBean("order1"); System.out.println("引用配置->" + order1); Order order2 = (Order) ctx.getBean("order2"); System.out.println("autowite_byname->" + order2); Order order3 = (Order) ctx.getBean("order3"); System.out.println("autowite_bytype->" + order3); } }
输出:
引用配置->Order [id=8888, user=User [id=1001, name=说易事]]
autowite_byname->Order [id=8889, user=User [id=1001, name=说易事]]
autowite_bytype->Order [id=8890, user=User [id=1001, name=说易事]]