組件掃描以及自動裝配

組件掃描

運用組件掃描就不用添加bean標籤,直接使用註解就可以將類的實例化控制交給spring容器。組件掃描也需要添加context命名空間,但是添加的標籤不一樣。我們只需要將註解添加到要實例化的類的前面,spring就會將該類添加到spring容器中。

<?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
	https://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	https://www.springframework.org/schema/context/spring-context.xsd">


	
	<!-- 可以激活@Autowired@Resource @PostConstruct@PreDestory註解-->
	<!-- 可以激活更多註解,如@Component@controller@service@repository -->
	<!-- 該標籤隱式的包含了<context:annotation-config/> -->
	<!--此標籤用來掃描jee.pk2包中的所有類如果遇到@Component@controller@service@repository 這四個註解,就會創建bean,放入容器中-->
	<context:component-scan base-package="jee.pk2"></context:component-scan>
</beans>
//@Component(value="")可以指定備案的name,如果不指定,默認使用類名作爲那麼
@Component
public class DBClientDaoImpl  implements ClientDao{
	public void insert() {
		System.out.println("DBClientDao insert");
	}
}

自動裝配

自動裝配就是bean標籤添加一個outowire屬性,這個屬性有四個值分別是
在這裏插入圖片描述


	<!-- autowire="byName"爲這個bean的所有屬性,尋找和屬性名匹配的bean,然後注入依賴 -->
	<!-- autowire="byType"爲這個bean的所有屬性,尋找和屬性類型匹配的bean,然後注入依賴  -->
	<!-- autowire="constructor" 爲這個bean的構造器的所有參數,尋找和參數類型匹配的bean,然後注入依賴 -->
	<bean id="clientService" class="jee.pk3.ClientService" autowire="byType"></bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章