1. Bean管理的注解实现及例子
- ClassPath扫描与组件管理
- 类的自动检测与注册Bean
<context: annotation-config/>
- @Component, @Repository, @Service, @Controller
- @Required
- @AutoWired
- @Qualifier
- @Resource
1.1 ClassPath扫描与组件管理
- 从Spring3.0开始,Spring JavaConfig项目提供了很多特性,包括使用Java而不是XML定义bean,比如@Configuration,@Bean,@Import,@DependsOn
- @Component是一个通用注解,可用于任何bean
- @Repository,@Service,@Controller是更有针对性的注解
- @Repository 通常用于注解DAO类,即持久层
- @Service 通常用于注解Service曾,即服务层
- @Controller通常用于Controller类,即控制层(MVC)
- @Repository 通常用于注解DAO类,即持久层
1.1.1 元注解(Meta-annotations)
- 许多Spring提供的注解可以作为自己的代码,即元数据注解,元注解是一个简单的注解,可以应用到另一个注解
- 除了value(), 元注解还可以有其他的属性,允许定制
1.1.2 类的自动检测及Bean的注册
- Spring可以自动检测类并注册Bean到ApplicationContext中
- 为了能够检测这些类并注册相应的Bean,需要下面内容
<context: component-scan/>
包含<context: annotation-config/>
,通常在使用前者后,不用再使用后者- AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor也会被包含进来
1.1.3 <context: annotation-config/>
- 通过在基于XML的Spring配置如下标签(请注意包含上下文命名空间)
- 仅会查找在同一个applicationContext中的bean注解
1.1.4 使用过滤器进行自定义扫描
- 默认情况下,类被自动发现并注册bean的条件是:使用@Component,@Repository,@Service,@Controller注解或者使用@Component的自定义注解
- 可以通过过滤器修改上面的行为,如:下面例子的XML配置忽略所有的@Repository注解并用“Stub”代替
- 还可使用use-default-filters=”false”禁用自动发现与注册
1.2 定义Bean
- 扫描过程中组件被自动检测,那么Bean名称是由BeanNameGenerator生成的(@Component, @Repository, @Service, @Controller都会有个name属性用于显式设置Bean Name)
- 可自定义bean命名策略,实现BeanNameGenerator接口,并一定要包含一个无参数构造器
1.3 作用域(Scope)
- 通常情况下自动查找的Spring组件,其Scope是singleton,Spring2.5提供了一个标识Scope的注解@Scope
- 也可以自定义Scope策略,实现ScopeMetaDataResolver接口并提供一个无参构造器
1.4 代理方式
- 可以使用scoped-proxy属性指定代理,有三个值可选:no,interfaces,targetClass