IOC操作Bean管理2(基于XML)
XML自动装配
概念
根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
bean标签属性autowire有两个值:
- byName:根据属性名注入,这里id的名字要和属性的名字一样,否则找不到
- byType:根据属性类型注入
代码实例
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="emp" class="com.bean.BeanAutoWire.Emp" autowire="byName">
</bean>
<bean id="dept" class="com.bean.BeanAutoWire.Dept">
</bean>
</beans>
package com.bean.BeanAutoWire;
public class Dept {
@Override
public String toString() {
return "Dept{}";
}
}
package com.bean.BeanAutoWire;
public class Emp {
public Dept dept;
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
'}';
}
}
package com.bean.BeanAutoWire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanAutoWire {
public static void main(String args[]) {
ApplicationContext content =
new ClassPathXmlApplicationContext("BeanAutoWire.xml");
Emp emp = content.getBean("emp",Emp.class);
System.out.println(emp);
System.out.println(emp.dept.toString());
}
}
|