自动注入(自动装配)byName

byName需要给属性提供set方法

Dao

浅谈Spring6之自动(装配)注入byName和byType_自动装配

Service

浅谈Spring6之自动(装配)注入byName和byType_spring_02

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>

浅谈Spring6之自动(装配)注入byName和byType_spring_03

测试类
//auto
@Test
public void aotuWire(){
ApplicationContext aotu = new ClassPathXmlApplicationContext("springConfig.xml");
OrderService orderService = aotu.getBean("orderService", OrderService.class);
orderService.generate();

}

自动注入(自动装配)byType

自动装配是基于set方法的,根据类型进行自动装配的时候,在有效的配置文件当中,某种类型的实例只能有一个。

Dao

浅谈Spring6之自动(装配)注入byName和byType_spring_04

浅谈Spring6之自动(装配)注入byName和byType_spring_05

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();
}