1.从Spring2.0以后的版本中,Spring也引入了基于注解(Annotation)方式的配置,注解(Annotation)是JDK1.5中引入的一个新特性,用于简化Bean的配置,某些场合可以取代XML配置文件。开发人员对注解(Annotation)的态度也是萝卜青菜各有所爱,个人认为注解可以大大简化配置,提高开发速度,同时也不能完全取代XML配置方式,XML 方式更加灵活,并且发展的相对成熟,这种配置方式为大多数 Spring 开发者熟悉;注解方式使用起来非常简洁,但是尚处于发展阶段,XML配置文件和注解(Annotation)可以相互配合使用。
应某些人员的要求,本文章就分析Spring对注解(Annotation)的解析过程,如果你对注解还不熟悉,请参考:http://blog.csdn.net/chjttony/archive/2010/11/22/6026079.aspx中8以后的对于注解的简单介绍和前一篇博客中转载的对Spring注解基本知识介绍:http://blog.csdn.net/chjttony/archive/2011/03/29/6286144.aspx.
Spring IoC容器对于类级别的注解和类内部的注解分以下两种处理策略:
(1).类级别的注解:如@Component、@Repository、@Controller、@Service以及JavaEE6的@ManagedBean和@Named注解,都是添加在类上面的类级别注解,Spring容器根据注解的过滤规则扫描读取注解Bean定义类,并将其注册到Spring IoC容器中。
(2).类内部的注解:如@Autowire、@Value、@Resource以及EJB和WebService相关的注解等,都是添加在类内部的字段或者方法上的类内部注解,Spring IoC容器通过Bean后置注解处理器解析Bean内部的注解。
下面将根据这两种处理策略,分别分析Spring处理注解相关的源码。
2.AnnotationConfigApplicationContext对注解Bean初始化:
Spring中,管理注解Bean定义的容器有两个:AnnotationConfigApplicationContext 和AnnotationConfigWebApplicationContex。这两个类是专门处理Spring注解方式配置的容器,直接依赖于注解作为容器配置信息来源的IoC容器。AnnotationConfigWebApplicationContext是AnnotationConfigApplicationContext的web版本,两者的用法以及对注解的处理方式几乎没有什么差别,因此本文将以AnnotationConfigApplicationContext为例进行讲解。
AnnotationConfigApplicationContext的源码如下:
- public class AnnotationConfigApplicationContext extends GenericApplicationContext {
-
- private final AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(this);
-
- private final ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this);
-
- public AnnotationConfigApplicationContext() {
- }
-
-
- public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
- register(annotatedClasses);
- refresh();
- }
-
-
- public AnnotationConfigApplicationContext(String... basePackages) {
- scan(basePackages);
- refresh();
- }
-
- public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
- this.reader.setBeanNameGenerator(beanNameGenerator);
- this.scanner.setBeanNameGenerator(beanNameGenerator);
- }
-
- public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {
- this.reader.setScopeMetadataResolver(scopeMetadataResolver);
- this.scanner.setScopeMetadataResolver(scopeMetadataResolver);
- }
-
-
- public void register(Class<?>... annotatedClasses) {
- this.reader.register(annotatedClasses);
- }
-
-
- public void scan(String... basePackages) {
- this.scanner.scan(basePackages);
- }
- }
通过对AnnotationConfigApplicationContext的源码分析,我们了解到Spring对注解的处理分为两种方式:
(1).直接将注解Bean注册到容器中:
可以在初始化容器时注册;也可以在容器创建之后手动调用注册方法向容器注册,然后通过手动刷新容器,使得容器对注册的注解Bean进行处理。
(2).通过扫描指定的包及其子包下的所有类:
在初始化注解容器时指定要自动扫描的路径,如果容器创建以后向给定路径动态添加了注解Bean,则需要手动调用容器扫描的方法,然后手动刷新容器,使得容器对所注册的Bean进行处理。
接下来,将会对两种处理方式详细分析其实现过程。
3.AnnotationConfigApplicationContext注册注解Bean:
当创建注解处理容器时,如果传入的初始参数是具体的注解Bean定义类时,注解容器读取并注册。
(1).AnnotationConfigApplicationContext通过调用注解Bean定义读取器AnnotatedBeanDefinitionReader的register方法向容器注册指定的注解Bean,注解Bean定义读取器向容器注册注解Bean的源码如下:
-
- public void register(Class<?>... annotatedClasses) {
- for (Class<?> annotatedClass : annotatedClasses) {
- registerBean(annotatedClass);
- }
- }
-
- public void registerBean(Class<?> annotatedClass) {
- registerBean(annotatedClass, null, (Class<? extends Annotation>[]) null);
- }
-
- public void registerBean(Class<?> annotatedClass, Class<? extends Annotation>... qualifiers) {
- registerBean(annotatedClass, null, qualifiers);
- }
-
- public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
-
- AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
-
-
- ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
-
- abd.setScope(scopeMetadata.getScopeName());
-
- String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
-
- AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
-
-
-
- if (qualifiers != null) {
- for (Class<? extends Annotation> qualifier : qualifiers) {
-
- if (Primary.class.equals(qualifier)) {
- abd.setPrimary(true);
- }
-
-
- else if (Lazy.class.equals(qualifier)) {
- abd.setLazyInit(true);
- }
-
-
-
- else {
- abd.addQualifier(new AutowireCandidateQualifier(qualifier));
- }
- }
- }
-
- BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
-
- definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
-
- }
从上面的源码我们可以看出,注册注解Bean定义类的基本步骤:
a,需要使用注解元数据解析器解析注解Bean中关于作用域的配置。
b,使用AnnotationConfigUtils的processCommonDefinitionAnnotations方法处理注解Bean定义类中通用的注解。
c,使用AnnotationConfigUtils的applyScopedProxyMode方法创建对于作用域的代理对象。
d,通过BeanDefinitionReaderUtils向容器注册Bean。
下面我们继续分析这3步的具体实现过程
(2).AnnotationScopeMetadataResolver解析作用域元数据:
AnnotationScopeMetadataResolver通过processCommonDefinitionAnnotations方法解析注解Bean定义类的作用域元信息,即判断注册的Bean是原生类型(prototype)还是单态(singleton)类型,其源码如下:
-
- public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
- ScopeMetadata metadata = new ScopeMetadata();
- if (definition instanceof AnnotatedBeanDefinition) {
- AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
-
-
-
- Map<String, Object> attributes =
- annDef.getMetadata().getAnnotationAttributes(this.scopeAnnotationType.getName());
-
- if (attributes != null) {
- metadata.setScopeName((String) attributes.get("value"));
-
- ScopedProxyMode proxyMode = (ScopedProxyMode) attributes.get("proxyMode");
-
- if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
-
- proxyMode = this.defaultProxyMode;
- }
-
- metadata.setScopedProxyMode(proxyMode);
- }
- }
-
- return metadata;
- }
上述代码中的annDef.getMetadata().getAnnotationAttributes方法就是获取对象中指定类型的注解的值。
(3).AnnotationConfigUtils处理注解Bean定义类中的通用注解:
AnnotationConfigUtils类的processCommonDefinitionAnnotations在向容器注册Bean之前,首先对注解Bean定义类中的通用Spring注解进行处理,源码如下:
-
- static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {
-
- if (abd.getMetadata().isAnnotated(Primary.class.getName())) {
- abd.setPrimary(true);
- }
-
- if (abd.getMetadata().isAnnotated(Lazy.class.getName())) {
- Boolean value = (Boolean) abd.getMetadata().getAnnotationAttributes(Lazy.class.getName()).get("value");
- abd.setLazyInit(value);
- }
-
-
- if (abd.getMetadata().isAnnotated(DependsOn.class.getName())) {
- String[] value = (String[]) abd.getMetadata().getAnnotationAttributes(DependsOn.class.getName()).get("value");
- abd.setDependsOn(value);
- }
- }
(4).AnnotationConfigUtils根据注解Bean定义类中配置的作用域为其应用相应的代理策略:
AnnotationConfigUtils类的applyScopedProxyMode方法根据注解Bean定义类中配置的作用域@Scope注解的值,为Bean定义应用相应的代理模式,主要是在Spring面向切面编程(AOP)中使用。源码如下:
-
- static BeanDefinitionHolder applyScopedProxyMode(
- ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
-
- ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
-
- if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
- return definition;
- }
-
-
- boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
-
- return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
- }
这段为Bean引用创建相应模式的代理,如果在Spring面向切面编程(AOP)中涉及到再详细分析,这里不做深入的分析。
(5).BeanDefinitionReaderUtils向容器注册Bean:
BeanDefinitionReaderUtils向容器注册载入的Bean我们在第4篇博客中已经分析过,主要是校验Bean定义,然后将Bean添加到容器中一个管理Bean定义的HashMap中,这里就不做分析。
4.AnnotationConfigApplicationContext扫描指定包及其子包下的注解Bean:
当创建注解处理容器时,如果传入的初始参数是注解Bean定义类所在的包时,注解容器将扫描给定的包及其子包,将扫描到的注解Bean定义载入并注册。
(1).Spring中常用的注解:
a.Component注解:
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface Component {
- String value() default "";
- }
b.Service注解:
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Component
- public @interface Service {
- String value() default "";
- }
c.Controller注解:
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Component
- public @interface Controller {
- String value() default "";
- }
d.Repository注解:
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Component
- public @interface Repository {
- String value() default "";
- }
通过分析Spring这4个常用的注解源码,我们看到:@Service、@Controller和@Repository注解都添加了一个@Component注解,因此他们都属于@Component
注解。
(2).ClassPathBeanDefinitionScanner扫描给定的包及其子包:
AnnotationConfigApplicationContext通过调用类路径Bean定义扫描器ClassPathBeanDefinitionScanner扫描给定包及其子包下的所有类,主要源码如下:
- public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
-
- public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
- this(registry, true);
- }
-
-
-
- public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
-
- super(useDefaultFilters);
- Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
-
- this.registry = registry;
-
- if (this.registry instanceof ResourceLoader) {
- setResourceLoader((ResourceLoader) this.registry);
- }
- }
-
- public int scan(String... basePackages) {
-
- int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
-
- doScan(basePackages);
-
- if (this.includeAnnotationConfig) {
- AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
- }
-
- return this.registry.getBeanDefinitionCount() - beanCountAtScanStart;
- }
-
- protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
-
- Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
-
- for (String basePackage : basePackages) {
-
-
- Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
-
- for (BeanDefinition candidate : candidates) {
-
- ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
-
- candidate.setScope(scopeMetadata.getScopeName());
-
- String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
-
-
- if (candidate instanceof AbstractBeanDefinition) {
- postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
- }
-
- if (candidate instanceof AnnotatedBeanDefinition) {
-
- }
-
- if (checkCandidate(beanName, candidate)) {
- BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
-
- definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
- beanDefinitions.add(definitionHolder);
-
- registerBeanDefinition(definitionHolder, this.registry);
- }
- }
- }
- return beanDefinitions;
- }
- ……
- }
类路径Bean定义扫描器ClassPathBeanDefinitionScanner主要通过findCandidateComponents方法调用其父类ClassPathScanningCandidateComponentProvider类来扫描获取给定包及其子包下的类。
(3).ClassPathScanningCandidateComponentProvider扫描给定包及其子包的类:
ClassPathScanningCandidateComponentProvider类的findCandidateComponents方法具体实现扫描给定类路径包的功能,主要源码如下:
5.AnnotationConfigWebApplicationContext载入注解Bean定义:
AnnotationConfigWebApplicationContext是AnnotationConfigApplicationContext的Web版,它们对于注解Bean的注册和扫描是基本相同的,但是AnnotationConfigWebApplicationContext对注解Bean定义的载入稍有不同,AnnotationConfigWebApplicationContext注入注解Bean定义源码如下:
-
- protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
-
- AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);
-
- ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
-
- BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
-
- ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
-
- if (beanNameGenerator != null) {
- reader.setBeanNameGenerator(beanNameGenerator);
- scanner.setBeanNameGenerator(beanNameGenerator);
- }
-
- if (scopeMetadataResolver != null) {
- reader.setScopeMetadataResolver(scopeMetadataResolver);
- scanner.setScopeMetadataResolver(scopeMetadataResolver);
- }
-
- String[] configLocations = getConfigLocations();
-
- if (configLocations != null) {
- for (String configLocation : configLocations) {
- try {
-
- Class<?> clazz = getClassLoader().loadClass(configLocation);
- if (logger.isInfoEnabled()) {
- logger.info("Successfully resolved class for [" + configLocation + "]");
- }
- reader.register(clazz);
- }
- catch (ClassNotFoundException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Could not load class for config location [" + configLocation +
- "] - trying package scan. " + ex);
- }
-
-
- int count = scanner.scan(configLocation);
- if (logger.isInfoEnabled()) {
- if (count == 0) {
- logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
- }
- else {
- logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
- }
- }
- }
- }
- }
- }