1. 程式人生 > >spring註解注入和context:component-scan

spring註解注入和context:component-scan

  一、spring註解

@Service告訴spring容器,這是一個Service類,標識持久層Bean元件,預設情況會自動載入它到spring容器中。 @Autowried註解告訴spring,這個欄位需要自動注入 @Scope指定此spring bean的scope是單例 @Repository註解指定此類是一個容器類,是DA層類的實現。標識持久層Bean元件 @Componet:基本註解,標識一個受Spring管理的Bean元件 @Controller:標識表現層Bean元件 

二、context.component-scan節點

 通常情況下我們在建立spring專案的時候在xml配置檔案中都會配置這個標籤,配置完這個標籤後,spring就會去自動掃描base-package對應的路徑或者該路徑的子包下面的java檔案,如果掃描到檔案中帶有@Service,@Component,@Repository,@Controller等這些註解的類,則把這些類註冊為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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

	<context:component-scan base-package="com.base" />
	<context:component-scan base-package="com.base.platform.attachment" />
	<!-- <context:property-placeholder location="/WEB-INF/uploadDir.properties" /> -->  
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>/WEB-INF/hibernate.properties</value>
				<value>/WEB-INF/uploadDir.properties</value>
			</list>
		</property>
	</bean>
</beans>
    <context:component-scan base-package="com.sparta.trans" use-default-filters="false">  

              <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>      

        </context:component-scan>

此時指定的include-filter沒有起到作用,只要把use-default-filter設定成false就可以了。這樣就可以避免在base-packeage配置多個包名來解決這個問題了。

這個檔案中beans根節點下只有一個context:component-scan節點,此節點有兩個屬性base-package屬性告訴spring要掃描的包,use-default-filters=”false”表示不要使用預設的過濾器,此處的預設過濾器,會掃描包含@Service,@Component,@Repository,@Controller註解修飾的類,use-default-filters屬性的預設值為true,這就意味著會掃描指定包下標有@Service,@Component,@Repository,@Controller的註解的全部類,並註冊成bean。 所以如果僅僅是在配置檔案中寫<context:component-scan base-package="com.sparta.trans"/> Use-default-filter此時為true時,那麼會對base-package包或者子包下所有的java類進行掃描,並把匹配的java類註冊成bean。

所以這用情況下可以發現掃描的力度還是挺大的,但是如果你只想掃描指定包下面的Controller,那該怎麼辦?此時子標籤<context:incluce-filter>就可以發揮作用了。

這樣就會只掃描base-package指定下的有@Controller下的Java類,並註冊成bean。