原文地址:http://blog.fawnanddoug.com/2012/08/how-those-spring-enable-annotations-work.html

Spring's Java Config is a great way to configure your application without writing a lot of configuration code.  One reason is those awesome @Enable* annotations that let you magically set up things like Transactions (@EnableTransactionManagement), Spring MVC (@EnableWebMvc) or timed jobs (@EnableScheduling) with a simple class level annotation on your configuration class. These simple statements provide a lot of functionality but their machinations are fairly obscure.  On the one hand, it's great to get so much functionality for so little work, but on the other hand, if you don't understand how something works it makes debugging and problem solving much harder.  I couldn't find any posts or documents that covered how those annotations work so I figured I would write up one based on the research I did while debugging.  I don't work for Spring and I didn't write any of this code so please post any corrections or improvements in the comments and I'll update the post.

Design Goals

From what I can tell, the design goal of those @Enable* annotations is to allow the user set up complex functionality with a minimal amount of code.  In addition, it seems clear that users must be able to use either a  simple default or be allowed to manually configure that code.  Finally, the complexities of the code are intended to be hidden from the user.  In short, let the user set up a lot of beans and optionally configure them without having to know the details of those beans (or really what's being set up).  I think there are a lot of pros (and some cons) to this approach but I'll discuss that at the end.

Case #1: @EnableScheduling (importing an @Configuration class)

The first thing to note is that the @Enable* annotations are not magic.  Nothing in the Bean Factory knows anything about them specifically and there are no dependencies in the Bean Factory classes between the core functionality and specific annotations (like @EnableWebMvc) or the jars they're stored in (like spring-web).  Let's take a look at @EnableScheduling and see how it works.  You might have a MainConfig class that looks like this:

1
2
3
4
5
@Configuration
@EnableScheduling
public class MainConfig {
// some beans go in here
}

There's nothing special in the above. Just a standard Java Config that's annotated with @EnableScheduling. @EnableScheduling lets you execute certain methods at a set frequency. For example, you can run BankService.sendMoneyToDoug() every 20 minutes.   The @EnableScheduling annotation itself looks like this:

1
2
3
4
5
6
7
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
@Documented
public @interface EnableScheduling {
 
}

If we look at the annotation above, we can see that it is just a standard Class level annotation (@Target/@Retention) that should be included in JavaDocs (@Documented), but it has one Spring-specific annotation: @Import.  @Import is the key that ties everything together.  In this case, since our MainConfig is annotated as @EnableScheduling, when the Bean Factory is parsing the file (technically the ConfigurationClassPostProcessor is parsing it) it will also find the @Import(SchedulingConfiguration.class) annotation and it will import the class defined in the value.  In this case SchedulingConfiguration.  What does it mean to import?  Well, in this case it's just treated as another Spring bean.  SchedulingConfiguration is actually annotated as @Configuration, so the Bean Factory will see it as another configuration class and all of the beans defined in that class will get pulled into your Application Context just as if you had defined another @Configuration class yourself.  If we inspect SchedulingConfiguration we can see that it only defines one bean (a Post Processor) which does the scheduling we described above.

1
2
3
4
5
6
7
8
9
10
@Configuration
public class SchedulingConfiguration {
 
 @Bean(name=AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
 @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
 public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
  return new ScheduledAnnotationBeanPostProcessor();
 }
 
}

OK, but what if I want to configure the beans defined in SchedulingConfiguration?  Well, at this point we're just dealing with regular beans.  So the same mechanisms that you would use for any other beans apply here.  In this case, the ScheduledAnnotationBeanPostProcessor uses a standard Spring Application Event to find out when the Application Context is refreshed.  When this happens it checks to see if any beans implement SchedulingConfigurer and if so, uses those beans to configure itself.  This is not at all intuitive (or easy to find with an IDE) but it is completely separated from the Bean Factory and is a fairly common pattern for a bean to be used to configure another bean.  And now that we can connect all of the dots it is (somewhat) easy to find (or you could google the documentation or read the JavaDocs).

Case #2: @EnableTransactionManagement (importing an ImportSelector)

In the previous case we discussed how an annotation like @EnableScheduling can use @Import to pull in another @Configuration Class and make all of its beans available (and configurable) to your application. But what happens if you want to load a different set of beans based on some configuration?  @EnableTransactionManaged is a good example of this.  You might have a MainConfig class that looks like this:
 
1
2
3
4
5
@Configuration
@EnableTransactionManagement(mode=AdviceMode.ASPECTJ)
public class MainConfig {
// some beans
}
 
Once again, there's  nothing special in the above. Just a standard Java Config that's annotated with @EnableTransactionManagement. The only thing that's a little different from the previous example is that the user specified a parameter to the annotation (mode=AdviceMode.ASPECTJ).  The @EnableTransactionManagement annotation itself looks like this:

1
2
3
4
5
6
7
8
9
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
 boolean proxyTargetClass() default false;
 AdviceMode mode() default AdviceMode.PROXY;
 int order() default Ordered.LOWEST_PRECEDENCE;
}

As before, a fairly standard annotation, although this time it has some parameters.  However, I mentioned previously that the @Import annotation was the key that ties everything together and that is true once again.  The distinction though, is that this time we are importing TransactionManagementConfigurationSelector.class which is not a class that is annotated with @Configuration.  TransactionManagementConfigurationSelector is a class that implements ImportSelector.  The purpose of ImportSelector is to allow your code to choose which configuration classes to load at runtime.  It has one method that takes some metadata about an annotation and returns an array of class names.  In this case, the TransactionManagementConfigurationSelector looks at the mode and returns some classes based on the mode:

1
2
3
4
5
6
7
8
9
10
protected String[] selectImports(AdviceMode adviceMode) {
 switch (adviceMode) {
  case PROXY:
   return new String[] { AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName() };
  case ASPECTJ:
   return new String[] { TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME };
  default:
   return null;
 }
}

Most of these classes are @Configuration classes (e.g. ProxyTransactionManagementConfiguration) so we know that they'll work like before, but some of them are not (let's ignore those for now).  For the @Configuration classes they get loaded and configured in the exact same way that we previously saw.  So in short, we can use @Import with an @Configuration class to load a standard set of beans or we can use @Import with an ImportSelector to load a set of beans that are decided at run time.  Sweet! But what about those classes we ignored?

Case #3: @EnableAspectJAutoProxy (importing at the Bean Definition Level)

@Import supports one last case which is when you want to deal with a Bean Registry (Factory) directly. If you need to manipulate the Bean Factory or work with beans at the Bean Definition level then this case is for you and it's very similar to the ones above.  Your MainConfig might look like:

1
2
3
4
5
@Configuration
@EnableAspectJAutoProxy
public class MainConfig {
// some beans
}

Once again, there's nothing special in the above. Just a standard Java Config that's annotated with @EnableAspectJAutoProxy.  Here's the source for @EnableAspectJAutoProxy:

1
2
3
4
5
6
7
8
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
 boolean proxyTargetClass() default false;
 
}

As before, the @Import is the key, but this time it's pointing to AspectJAutoProxyRegistrar which is neither an @Configuration class nor implements ImportSelector.  The trick this time is that it implements ImportBeanDefinitionRegistrar.  This interface gives access to the Bean Registry and Annotation Metadata so that we can manipulate the registry at runtime based off of the parameters in the annotation.  If you look at the previous case you can see that the classes we ignored were also ImportBeanDefinitionRegistrars.  These classes directly manipulate the Bean  Factory for those times when @Configuration classes aren't enough.

So now we've covered all of the different ways the @Enable* annotations use @Import to pull various beans into your Application Context.  They either pull in a set of @Configuration classes directly and all of the beans from those classes get imported into your Application Context.  Or they pull in an ImportSelector which chooses a set of @Configuration classes at runtime and imports those beans into your Application Context.  Or finally, they pull in an ImportBeanDefinitionRegistrars which can directly work with the Bean Factory at the Bean Definition level.

Conclusion

In general I think this approach to importing beans into an Application Context is great because it makes set up very easy for the developer.  Unfortunately it obscures how to find the available options and how to configure them.  In addition, it doesn't directly take advantage of the IDE so it's hard to tell which beans are being created (and why).  However, now that we know about the @Import annotation we can use our IDE to dig a little into each Annotation and its related configuration classes and understand which beans are being created, how they're being added to your Application Context and how to configure them.  I hope this helps! Please leave comments to let me know what you think and what I've missed / messed up.

How those spring enable annotations work--转的更多相关文章

  1. Spring Enable annotation – writing a custom Enable annotation

    原文地址:https://www.javacodegeeks.com/2015/04/spring-enable-annotation-writing-a-custom-enable-annotati ...

  2. Spring Enable* 注解

    Spring提供了一系列以Enable开头的注解,这些注解本质上是激活Spring的某些管理功能.比如,EnableWebMvc. 这个注解引入了MVC框架在Spring 应用中需要用到的所有bean ...

  3. Spring Project Annotations

       Project  Annotation  Discovered By  Package     Target(s)  Parameters  Notes . AspectJ @EnableSpr ...

  4. Spring Enable*高级应用及原理

    Enable* 之前的文章用到了一些Enable*开头的注解,比如EnableAsync.EnableScheduling.EnableAspectJAutoProxy.EnableCaching等, ...

  5. Spring Enable高级应用及原理

    Enable* 之前的文章用到了一些Enable*开头的注解,比如EnableAsync.EnableScheduling.EnableAspectJAutoProxy.EnableCaching等, ...

  6. 译:Spring框架参考文档之IoC容器(未完成)

    6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...

  7. Developing JSF applications with Spring Boot

    Developing JSF applications with Spring Boot Spring Boot can leverage any type of applications, not ...

  8. spring@PropertySource用法

    测试例子 package com.hjzgg.auth.config; import org.springframework.beans.factory.annotation.Autowired; i ...

  9. Spring框架文档与API(4.3.6版本)

    http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/ Table of Contents I ...

随机推荐

  1. 微信企业号 获取AccessToken

    目录 1. AccessToken介绍 2. 示例代码 1. AccessToken介绍 1.1 什么是AccessToken AccessToken即访问凭证,业务服务器每次主动调用企业号接口时需要 ...

  2. 死磕内存篇 --- JAVA进程和linux内存间的大小关系

    运行个JAVA 用sleep去hold住 package org.hjb.test; public class TestOnly { public static void main(String[] ...

  3. 【AR实验室】OpenGL ES绘制相机(OpenGL ES 1.0版本)

    0x00 - 前言 之前做一些移动端的AR应用以及目前看到的一些AR应用,基本上都是这样一个套路:手机背景显示现实场景,然后在该背景上进行图形学绘制.至于图形学绘制时,相机外参的解算使用的是V-SLA ...

  4. ABP文档 - Mvc 视图

    文档目录 本节内容: 简介 AbpWebViewPage 基类 简介 ABP通过nuget包Abp.Web.Mvc集成到Mvc视图里,你可以像往常那样创建常规的视图. AbpWebViewPage 基 ...

  5. 探究@property申明对象属性时copy与strong的区别

    一.问题来源 一直没有搞清楚NSString.NSArray.NSDictionary--属性描述关键字copy和strong的区别,看别人的项目中属性定义有的用copy,有的用strong.自己在开 ...

  6. Android Ormlite 学习笔记2 -- 主外键关系

    以上一篇为例子,进行主外键的查询 定义Users.java 和 Role.java Users -- Role 关系为:1对1 即父表关系 Role -- Users 关系为:1对多 即子表关系 下面 ...

  7. 基于netty http协议栈的轻量级流程控制组件的实现

    今儿个是冬至,所谓“冬大过年”,公司也应景五点钟就放大伙儿回家吃饺子喝羊肉汤了,而我本着极高的职业素养依然坚持留在公司(实则因为没饺子吃没羊肉汤喝,只能呆公司吃食堂……).趁着这一个多小时的时间,想跟 ...

  8. 学习ASP.NET Core, 怎能不了解请求处理管道[5]: 中间件注册可以除了可以使用Startup之外,还可以选择StartupFilter

    中间件的注册除了可以借助Startup对象(DelegateStartup或者ConventionBasedStartup)来完成之外,也可以利用另一个叫做StartupFilter的对象来实现.所谓 ...

  9. C++中的引用

    一,C++中引用的基础知识 1.引用的基本概念 1.所谓的引用其实就是对变量起“别名”.引用和变量对应得是相同的内存,修改引用的值,变量的值也会改变,和指针类似. 2.引用在定义的时候必须要初始化,初 ...

  10. SQL Server2008R2 在windows8上安装,出现“兼容性”和 “执行未经授权的操作”的错误!

    本人是windows8.1的操作系统,亲测安装成功 解决方法如下: 1.卸载干净sql Server2008r2,包括注册表内容,删除c盘下的安装路径! 2.关闭防火墙(这步很重要) 3.断开网络连接 ...