spring ioc之最基礎最簡單最明瞭的annotation注入

1、配置applicationContext.xml開啓註解


<?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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 註解使用示例 -->
<!-- 開啓註解 -->
<context:annotation-config />

</beans>


2、自動註冊bean註解


<?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:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 開啓自動檢測bean註解 -->
<!-- base-package表示會掃描com.test.bean及其所有子包,對使用了自動註冊註解的類進行自動註冊 -->
<context:component-scan base-package="com.test.bean">
<!-- 過濾哪些類需要被註冊,type有5種類型 -->
<!-- assignable表示掃描派生與expression指定類型的類 -->
<!-- annotation表示掃描使用了指定註解標註的類 -->
<!-- aspectj表示掃描與expression指定的AspectJ表達式匹配的類 -->
<!-- custom表示使用自定義的TypeFilter實現類 -->
<!-- regex表示過濾expression指定的正則表達式相匹配的類 -->
<context:include-filter type="assignable"
expression="com.test.bean.TestAnnotation" />
<!-- 過濾哪些類不能被註冊 -->
<context:exclude-filter type="assignable"
expression="com.test.bean.Ssb" />
</context:component-scan>

</beans>


3、將該類自動註冊爲bean並將id命名爲myService,如果不指定默認爲第一個字母小寫


/**
* @Component 標誌該類爲Spring組件
* @Controller 標誌該類爲Spring MVC Controller
* @Repository 標誌該類爲數據倉庫
* @Service 標誌該類爲服務
*/
//
@Service("myService")

public class MyServiceImpl implements MyService{

................
}


4、在控制器中注入



//如果是通過@Component注入普通bean,
//那麼需要在普通bean中加入默認的構造器,否則將無法實力化bean
public class MyControoler{
@Resource
private MyService myService;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章