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>
相关文章
相关标签/搜索