Container的職責在於創建、配置與組裝bean,昨天我們學到了
如何使用註解的方式來將bean設置到container中
今日將討論如何使用@Autowire註解將bean組裝
往往一個組件會需要其他的組件組成,例如一個LoginService可能會調用到UserDao、EmailService等等,而@Autowired就是告訴container哪個元件要進行配置
@Controller
public class EmpServlet {
@Autowired
private EmpService empService;
public void doGet(){
empService.saveEmpInfo();
}
}
@Service
public class EmpService {
@Autowired
private EmpDao empDao;
public void saveEmpInfo(){
System.out.println("調用EmpService中saveEmpInfo方法");
empDao.save();
}
}
@Repository
public class EmpDao {
public void save() {
System.out.println("調用EmpDao中save方法");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 啟動註解掃描,掃描com.swj package之下的類 -->
<context:component-scan base-package="com.swj"></context:component-scan>
</beans>
@Test
public void testDay15(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean15.xml");
System.out.println("容器啟動完成....");
EmpServlet controller = ioc.getBean("empServlet",EmpServlet.class);
controller.doGet();
}
Result
可以指定要找container中哪一個id
當EmpService的類別不只一個且EmpServlet中EmpService的變數名稱不等於empService時
@Controller
public class EmpServlet {
@Autowired
private EmpService empService123;
public void doGet(){
empService123.saveEmpInfo();
}
}
@Service
public class EmpServiceEnhance extends EmpService {
@Autowired
private EmpDao empDao;
public void saveEmpInfo(){
System.out.println("調用EmpServiceEnhance中saveEmpInfo方法");
empDao.save();
}
}
Result
透過@Qualifer之後
@Controller
public class EmpServlet {
@Autowired
@Qualifier("empServiceEnhance")
private EmpService empService123;
public void doGet(){
empService123.saveEmpInfo();
}
}
Result
default為true,所以@Autowired只要找不到bean就會拋出異常,設為false後可以避免找不到
@Controller
public class EmpServlet {
@Autowired(required = false)
@Qualifier("empService456")
private EmpService empService;
public void doGet(){
System.out.println("調用doGet..."+empService);
//empService123.saveEmpInfo();
}
}
Result