自动注入(自动装配)byName
byName需要给属性提供set方法
Dao
Service
SpringConfig.xml配置
<!--dao-->
<!-- (id不能随便写,写set方法名称)-->
<bean id="orderDao" class="com.spring6.dao.OrderDao"></bean>
<!--service-->
<!-- 根据名字自动装配-->
<bean id="orderService" class="com.spring6.service.OrderService" autowire="byName">
</bean>
测试类
//auto
@Test
public void aotuWire(){
ApplicationContext aotu = new ClassPathXmlApplicationContext("springConfig.xml");
OrderService orderService = aotu.getBean("orderService", OrderService.class);
orderService.generate();
}
自动注入(自动装配)byType
自动装配是基于set方法的,根据类型进行自动装配的时候,在有效的配置文件当中,某种类型的实例只能有一个。
Dao
Service
public class CustomerService {
private UserDao userDao;
private testDao testdao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setTestdao(testDao testdao) {
this.testdao = testdao;
}
public void saveUser(){
userDao.insert();
testdao.insert();
}
}
SpringConfig.xml
<!--根据类型自动装配-->
<!-- dao-->
<bean class="com.spring6.dao.UserDao"></bean>
<bean class="com.spring6.dao.testDao"></bean>
<!-- service-->
<bean id="cser" class="com.spring6.service.CustomerService" autowire="byType"></bean>
测试类
@Test
public void aotuWire(){
ApplicationContext auto = new ClassPathXmlApplicationContext("springConfig.xml");
CustomerService cser = auto.getBean("cser", CustomerService.class);
cser.saveUser();
}