public class CatDAO {
public void saveCat(){
System.out.println("保存猫猫");
}
}
这是第二个类,在这个类中引用了第一个类
public class CatService {
private CatDAO catDAO;
public CatDAO getCatDAO(){
return catDAO;
}
public void setCatDAO(CatDAO catDAO){
this.catDAO = catDAO;
}
}
这是第三个类,在第三个类中引用了第二个类
public class CatWeb {
private CatService catService;
public CatService getCatService(){
return catService;
}
public void setCatService(CatService catService){
this.catService = catService;
}
}
类创建好了,我们来配置
<bean id="catDao" class="com.spring.DAO.CatDAO"/>
<bean autowire="byType" id="catService" class="com.spring.Service.CatService"/>
<bean autowire="byType" id="catWeb" class="com.spring.Web.CatWeb"/>
这里我们看到了autowire属性,它有“byType”和“byName”两个属性,需要注意的是,在使用“byType”时,在配置文件中只能有一个相同的类型,如果有多个,则会无法判断,从而出现错误。
让我们来测试一下
@Test
public void autoConfiguration(){
//创建容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
//得到对象
CatWeb catWeb = ioc.getBean("catWeb", CatWeb.class);
CatDAO catDAO = catWeb.getCatService().getCatDAO();
catDAO.saveCat();
}
执行这个测试类,得到以下输出,说明我们的配置是成功的
这样,我们就完成了bean对象的自动装配。