How those spring enable annotations work
来源:互联网 发布:iphone数据恢复软件 编辑:程序博客网 时间:2024/04/30 13:03
出处:http://blog.fawnanddoug.com/2012/08/how-those-spring-enable-annotations-work.html(链接已失效,我从Google快照打开的)
How those Spring @Enable* Annotations work
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:@Configuration@EnableSchedulingpublic 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:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Import(SchedulingConfiguration.class)@Documentedpublic @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.
@Configurationpublic 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:
@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:
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:
@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:
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:@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:
@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. 0 0
- How those spring enable annotations work
- How to use Spring @Component, @Repository, @Service and @Controller Annotations?
- Spring Annotations
- spring annotations
- Spring Annotations
- Those Days After Spring Festival
- How does netstat work
- How Web Forms Work
- How Servlet Containers Work?
- How Servlet Containers Work
- How Servlet Containers Work
- How Servlet Containers Work
- How does XVCL work?
- How does JNA work?
- How SKBs Work
- How does cas work
- How SKBs work
- how does wifi work?
- 杭电ACM 三 选地盖房防水淹(Math.ceil)
- 配置ST_Geometry查询
- Altium 不同原理图之间的网络标号没有连线的问题 error:Duplicate Net Names
- Android TextView实现跑马灯效果
- IOS坐标体系与旋转
- How those spring enable annotations work
- Mybatis resultMap支持继承
- 【Ubuntu】Ubuntu 硬盘“分区”图文教程(用于光盘,U盘安装Ubuntu)
- Json学习笔记
- Animation 动画
- spring bean源码简单解析
- java编程思想并发学习笔记(rocket and rockets)
- leetcode_147_Insertion Sort Lis
- 模仿淘宝京东数量选择器