spring--(13)基於註解的方式配置bean

spring中配置bean的方式有三種:
1>經過工廠方法
2>經過factoryBean方法配置
3>經過註解的方式配置
因爲在開發中註解的方式使用得最多,所以,這裏僅僅介紹註解的方式。
spring能夠自動掃描classpath下特定註解的組件,組件包括:
@Component:基本組件,標識一個受spring管理的組件,能夠應用於任何層次
@Repository:標識持久層組件,表示數據庫訪問
@Service:標識業務層組件
@Controller:標識控制層組件
對於掃描到的組件,spring有默認的命名規則,即類名的首字母小寫;固然也能夠在註解中經過使用value屬性值標識組件的名稱。
舉例,以下兩種形式是同樣的
//1.註解方式配置beanspring

@Service
public class Address {
	private String city;
	private String street;
}

//2.xml方式配置bean數據庫

<bean id="address" class="com.test.autowired.Address">
	</bean>

當在工程中的某些類上使用了註解後,須要在spring的配置文件中聲明context:component-scan
1>base-package:指定一個須要掃描的基類包,spring容器會掃描這個基類包及其全部的子包裏面的全部類。
2>當須要掃描多個包時,能夠使用逗號分隔。
3>若是僅僅但願掃描指定包下面部分的類,而不是全部的類,能夠使用resource-pattern屬性過濾特定的類。
示例1:掃描com.test.annotation和com.test.autowired兩個包及其子包下面全部的class
xml文件以下express

<!-- 掃描com.test.annotation包和com.test.autowired包及其子包全部的類   -->
	<context:component-scan base-package="com.test.annotation,com.test.autowired">
	</context:component-scan>

示例2:掃描com.test.annotation包下子包repository下全部的類
xml配置文件以下spa

<!-- 掃描com.test.annotation包下子包repository下全部的類 -->
	<context:component-scan base-package="com.test.annotation"
	resource-pattern="repository/*.class">
	</context:component-scan>

示例3:不包含某些子節點(方式一:按照註解來包含與排除)code

<!-- 掃描com.test.annotation包下全部的類,排除@Repository註解(其餘註解相似) -->
	<context:component-scan base-package="com.test.annotation">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
	</context:component-scan>

示例4:只包含某些子節點(方式一:按照註解來包含與排除)component

<!-- 掃描com.test.annotation包下全部的類,只包含@Repository註解(其餘註解相似) -->
	<!-- 注意:此時須要設置use-default-filters="false",false表示按照下面的過濾器來執行;true表示按照默認的過濾器來執行 -->
	<context:component-scan base-package="com.test.annotation" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
	</context:component-scan>

示例5:不包含某些子節點(方式二:按照類名/接口名來包含與排除)xml

<!-- 掃描com.test.annotation包下全部的類,不包含UserService接口及其全部實現類 -->
	<context:component-scan base-package="com.test.annotation">
		<context:exclude-filter type="assignable" expression="com.test.annotation.service.UserService"/>
	</context:component-scan>

示例6:只包含某些子節點(方式二:按照類名/接口名來包含與排除)接口

<!-- 掃描com.test.annotation包下全部的類,只包含UserRepository接口及其全部實現類 -->
	<context:component-scan base-package="com.test.annotation" use-default-filters="false">
		<context:include-filter type="assignable" expression="com.test.annotation.repository.UserRepository"/>
	</context:component-scan>
相關文章
相關標籤/搜索