Spring官方:Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系
可以自动让Spring通过检查BeanFactory
中的内容,来替我们指定bean的协作者(其他被依赖的bean)。由于autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥!
1.applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="engine" class="com.yw.test07.Engine"></bean>
<bean id="engine3" class="com.yw.test07.Engine2"></bean>
<bean id="car" class="com.yw.test07.Car" autowire="byName" />
<bean id="car2" class="com.yw.test07.Car" autowire="byType" />
</beans>
2.
package com.yw.test07;
public class Engine
{
}
package com.yw.test07;
public class Engine2
{
}
package com.yw.test07;
public class Car
{
private Engine engine;
private Engine2 engine2;
public Engine getEngine()
{
return engine;
}
public void setEngine(Engine engine)
{
this.engine = engine;
}
public Engine2 getEngine2()
{
return engine2;
}
public void setEngine2(Engine2 engine2)
{
this.engine2 = engine2;
}
@Override
public String toString()
{
return "Car [engine=" + engine + ", engine2=" + engine2 + "]";
}
}
package com.yw.test07;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test
{
public static void main(String[] args)
{
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:com/yw/test07/applicationContext.xml");
// 自动装配 byName
Car car = (Car) app.getBean("car");
System.out.println("car=" + car);
// 自动装配 byType
Car car2 = (Car) app.getBean("car2");
System.out.println("car2=" + car2);
}
}
3.运行如图