zoukankan      html  css  js  c++  java
  • Spring使用_进阶

    概述

      本文主要写了几个关于Spring Aware,多线程,计划任务(定时任务),条件注解,组合注解,元注解,Spring测试的小例子以及关于@Enable*注解的工作原理的理解。


    Spring Aware

      简介:

        Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器,如Google Guice,这是Bean之间的耦合度很低。

        但是在实际项目中,有时会不可避免的要用到Spring容器本身的功能资源,这是你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,这就是Spring Aware。

        其实Spring Aware本来就是Spring设计用来框架内部使用的,若使用了Spring Aware,你的Bean将会和Spring框架耦合。

      例子:

     1 package com.wisely.highlight_spring4.ch3.aware;
     2 
     3 import org.apache.commons.io.IOUtils;
     4 import org.springframework.beans.factory.BeanNameAware;
     5 import org.springframework.context.ResourceLoaderAware;
     6 import org.springframework.core.io.Resource;
     7 import org.springframework.core.io.ResourceLoader;
     8 import org.springframework.stereotype.Service;
     9 
    10 import java.io.IOException;
    11 
    12 /**
    13  * Spring Aware演示Bean
    14  * 实现BeanNameAware、ResourceLoaderAware接口,获得Bean名称和资源加载的服务。
    15  */
    16 @Service
    17 public class AwareService implements BeanNameAware, ResourceLoaderAware {//1
    18 
    19     private String beanName;
    20     private ResourceLoader loader;
    21     //实现ResourceLoaderAware需重写setResourceLoader方法
    22     @Override
    23     public void setResourceLoader(ResourceLoader resourceLoader) {//2
    24         this.loader = resourceLoader;
    25     }
    26     //实现BeanNameAware需重写setBeanName方法
    27     @Override
    28     public void setBeanName(String name) {//3
    29         this.beanName = name;
    30     }
    31 
    32     public void outputResult() {
    33         System.out.println("Bean的名称为:" + beanName);
    34         Resource resource = loader.getResource("classpath:com/wisely/highlight_spring4/ch3/aware/test.txt");
    35         try {
    36             System.out.println("ResourceLoader加载的文件内容为: " + IOUtils.toString(resource.getInputStream()));
    37         } catch (IOException e) {
    38             e.printStackTrace();
    39         }
    40     }
    41 }
    Spring Aware演示Bean
     1 package com.wisely.highlight_spring4.ch3.aware;
     2 
     3 import org.springframework.context.annotation.ComponentScan;
     4 import org.springframework.context.annotation.Configuration;
     5 
     6 /**
     7  * 配置类
     8  */
     9 @Configuration
    10 @ComponentScan("com.wisely.highlight_spring4.ch3.aware")
    11 public class AwareConfig {
    12 
    13 }
    配置类
     1 package com.wisely.highlight_spring4.ch3.aware;
     2 
     3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     4 
     5 /**
     6  * 运行
     7  */
     8 public class Main {
     9     public static void main(String[] args) {
    10         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
    11         AwareService awareService = context.getBean(AwareService.class);
    12         awareService.outputResult();
    13         context.close();
    14     }
    15 }
    运行

    多线程

      简介:

        Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程,使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。

        而实际开发中任务一般是非阻碍的(异步的),所以我们要在配置类中通过@EnableAsync开启对异步任务的支持,并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务。

      例子:

     1 package com.wisely.highlight_spring4.ch3.taskexecutor;
     2 
     3 import org.springframework.scheduling.annotation.Async;
     4 import org.springframework.stereotype.Service;
     5 
     6 /**
     7  * 任务执行类
     8  */
     9 @Service
    10 public class AsyncTaskService {
    11     /**
    12      * 通过@Async注解表明该方法是一个异步方法,如果注解在类级别,则表明该类所有的方法都是异步方法。
    13      * 而这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor。
    14      * @param i
    15      */
    16     @Async
    17     public void executeAsyncTask(Integer i){
    18         System.out.println("执行异步任务: "+i);
    19     }
    20 
    21     @Async
    22     public void executeAsyncTaskPlus(Integer i){
    23         System.out.println("执行异步任务+1: "+(i+1));
    24     }
    25 
    26 }
    任务执行类
     1 package com.wisely.highlight_spring4.ch3.taskexecutor;
     2 
     3 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
     4 import org.springframework.context.annotation.ComponentScan;
     5 import org.springframework.context.annotation.Configuration;
     6 import org.springframework.scheduling.annotation.AsyncConfigurer;
     7 import org.springframework.scheduling.annotation.EnableAsync;
     8 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
     9 
    10 import java.util.concurrent.Executor;
    11 
    12 /**
    13  * 配置类
    14  */
    15 @Configuration
    16 @ComponentScan("com.wisely.highlight_spring4.ch3.taskexecutor")
    17 @EnableAsync //使用@EnableAsync注解开启异步任务支持
    18 public class TaskExecutorConfig implements AsyncConfigurer {//实现AsyncConfigurer接口
    19 
    20     /**
    21      * 重写AsyncConfigurer接口的getAsyncExecutor方法,并返回一个ThreadPoolTaskExecutor
    22      * 这样就可以获得一个基于线程池的TaskExecutor
    23      * @return
    24      */
    25     @Override
    26     public Executor getAsyncExecutor() {
    27         ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    28         //设置核心池大小
    29         taskExecutor.setCorePoolSize(5);
    30         //设置最大池大小
    31         taskExecutor.setMaxPoolSize(10);
    32         //设置队列容量
    33         taskExecutor.setQueueCapacity(25);
    34         //初始化
    35         taskExecutor.initialize();
    36         return taskExecutor;
    37     }
    38 
    39     @Override
    40     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    41         return null;
    42     }
    43 }
    配置类
     1 package com.wisely.highlight_spring4.ch3.taskexecutor;
     2 
     3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     4 
     5 /**
     6  * 运行
     7  */
     8 public class Main {
     9     public static void main(String[] args) {
    10         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
    11         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
    12         for (int i = 0; i < 10; i++) {
    13             asyncTaskService.executeAsyncTask(i);
    14             asyncTaskService.executeAsyncTaskPlus(i);
    15         }
    16         context.close();
    17     }
    18 }
    运行

    计划任务(定时任务)

      简介:

        从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。

        Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。

      例子:

     1 package com.wisely.highlight_spring4.ch3.taskscheduler;
     2 
     3 import org.springframework.scheduling.annotation.Scheduled;
     4 import org.springframework.stereotype.Service;
     5 
     6 import java.text.SimpleDateFormat;
     7 import java.util.Date;
     8 
     9 /**
    10  * 计划任务执行类
    11  */
    12 @Service
    13 public class ScheduledTaskService {
    14 
    15     private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    16 
    17     /**
    18      * 通过@Scheduled注解声明该方法是计划任务,使用fixedRate属性每隔固定时间执行。
    19      */
    20     @Scheduled(fixedRate = 5000)
    21     public void reportCurrentTime() {
    22         System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
    23     }
    24 
    25     /**
    26      * 1:使用cron属性可按照指定时间执行,这里是每天11点28分执行
    27      * 2:cron是UNIX和类UNIX(Linux)系统下的定时任务
    28      */
    29     @Scheduled(cron = "0 28 11 ? * *")
    30     public void fixTimeExecution() {
    31         System.out.println("在指定时间 " + dateFormat.format(new Date()) + "执行");
    32     }
    33 }
    计划任务执行类
     1 package com.wisely.highlight_spring4.ch3.taskscheduler;
     2 
     3 import org.springframework.context.annotation.ComponentScan;
     4 import org.springframework.context.annotation.Configuration;
     5 import org.springframework.scheduling.annotation.EnableScheduling;
     6 
     7 /**
     8  * 配置类
     9  */
    10 @Configuration
    11 @ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")
    12 @EnableScheduling //通过@EnableScheduling注解开启对计划任务的支持。
    13 public class TaskSchedulerConfig {
    14 
    15 }
    配置类
     1 package com.wisely.highlight_spring4.ch3.taskscheduler;
     2 
     3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     4 
     5 /**
     6  * 运行
     7  */
     8 public class Main {
     9     public static void main(String[] args) {
    10          AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
    11     }
    12 }
    运行

    条件注解(@Conditional)

      简介:

        一句话来说:@Conditional注解可以根据特定条件创建特定的Bean。

      例子:

     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 import org.springframework.context.annotation.Condition;
     4 import org.springframework.context.annotation.ConditionContext;
     5 import org.springframework.core.type.AnnotatedTypeMetadata;
     6 
     7 /**
     8  * 判断条件定义
     9  * 判断Linux的条件
    10  */
    11 public class LinuxCondition implements Condition {//实现Condition接口
    12 
    13     /**
    14      * 重写Condition接口的matches方法来构造判断条件
    15      * @param context
    16      * @param metadata
    17      * @return
    18      */
    19     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    20         return context.getEnvironment().getProperty("os.name").contains("Linux");
    21     }
    22 }
    判断条件定义_Linux
     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 import org.springframework.context.annotation.Condition;
     4 import org.springframework.context.annotation.ConditionContext;
     5 import org.springframework.core.type.AnnotatedTypeMetadata;
     6 
     7 /**
     8  * 判断条件定义
     9  * 判断Windows的条件
    10  */
    11 public class WindowsCondition implements Condition {//实现Condition接口
    12 
    13     /**
    14      * 重写Condition接口的matches方法来构造判断条件
    15      * @param context
    16      * @param metadata
    17      * @return
    18      */
    19     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    20         return context.getEnvironment().getProperty("os.name").contains("Windows");
    21     }
    22 }
    判断条件定义_Windows
    1 package com.wisely.highlight_spring4.ch3.conditional;
    2 
    3 /**
    4  * 不同系统下Bean的类
    5  * 接口
    6  */
    7 public interface ListService {
    8     public String showListCmd();
    9 }
    不同系统下Bean的类_接口
     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 /**
     4  * 不同系统下Bean的类
     5  * Linux下所要创建的Bean的类
     6  */
     7 public class LinuxListService implements ListService{
     8 
     9     @Override
    10     public String showListCmd() {
    11         return "ls";
    12     }
    13 }
    不同系统下Bean的类_Linux
     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 /**
     4  * 不同系统下Bean的类
     5  * Windows下所要创建的Bean的类
     6  */
     7 public class WindowsListService implements ListService {
     8 
     9     @Override
    10     public String showListCmd() {
    11         return "dir";
    12     }
    13 }
    不同系统下Bean的类_Windows
     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 import org.springframework.context.annotation.Bean;
     4 import org.springframework.context.annotation.Conditional;
     5 import org.springframework.context.annotation.Configuration;
     6 
     7 /**
     8  * 配置类
     9  */
    10 @Configuration
    11 public class ConditionConfig {
    12 
    13     /**
    14      * 通过@Conditional注解,符合Windows条件则实例化windowsListService
    15      * @return
    16      */
    17     @Bean
    18     @Conditional(WindowsCondition.class)
    19     public ListService windowsListService() {
    20         return new WindowsListService();
    21     }
    22 
    23     /**
    24      * 通过@Conditional注解,符合Linux条件则实例化linuxListService
    25      * @return
    26      */
    27     @Bean
    28     @Conditional(LinuxCondition.class)
    29     public ListService linuxListService() {
    30         return new LinuxListService();
    31     }
    32 }
    配置类
     1 package com.wisely.highlight_spring4.ch3.conditional;
     2 
     3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     4 
     5 /**
     6  * 运行
     7  */
     8 public class Main {
     9 
    10     public static void main(String[] args) {
    11         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
    12         ListService listService = context.getBean(ListService.class);
    13         System.out.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令为: " + listService.showListCmd());
    14         context.close();
    15     }
    16 }
    运行

    组合注解与元注解

      简介:

        从Spring2开始,为了响应JDK1.5推出的注解功能,Spring开始大量加入注解来替代xml配置。Spring的注解主要用来配置和注入Bean,以及AOP相关配置。

        随着注解的大量使用,尤其相同的多个注解用到各个类或者方法中,会相当繁琐。这就形成了所谓的样板代码(boilerplate code),是Spring涉及原则中要消除的代码。

        所谓的元注解其实就是可以注解到别的注解上的注解,被注解的注解称之为组合注解,组合主借具备注解在上面的元注解的功能。Spring的很多注解都可以作为元注解,而且Spring本身已经有很多组合注解。如@Configuration就是一个组合@Component注解,表明这个类其实也是一个Bean。

      例子:

     1 package com.wisely.highlight_spring4.ch3.annotation;
     2 
     3 import org.springframework.context.annotation.ComponentScan;
     4 import org.springframework.context.annotation.Configuration;
     5 
     6 import java.lang.annotation.*;
     7 
     8 /**
     9  * 组合注解
    10  */
    11 @Target(ElementType.TYPE)
    12 @Retention(RetentionPolicy.RUNTIME)
    13 @Documented
    14 @Configuration //组合@Configuration元注解
    15 @ComponentScan //组合@ComponentScan注解
    16 public @interface WiselyConfiguration {
    17     
    18     String[] value() default {}; //覆盖value参数
    19 
    20 }
    组合注解
     1 package com.wisely.highlight_spring4.ch3.annotation;
     2 
     3 import org.springframework.stereotype.Service;
     4 
     5 /**
     6  * 服务Bean
     7  */
     8 @Service
     9 public class DemoService {
    10     
    11     public void outputResult(){
    12         System.out.println("从组合注解配置照样获得的bean");
    13     }
    14 }
    服务Bean
     1 package com.wisely.highlight_spring4.ch3.annotation;
     2 
     3 /**
     4  * 配置类
     5  * 使用@WiselyConfiguration注解替代@Configuration和@ComponentScan注解。
     6  */
     7 @WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation")
     8 public class DemoConfig {
     9 
    10 }
    配置类
     1 package com.wisely.highlight_spring4.ch3.annotation;
     2 
     3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
     4 
     5 /**
     6  * 运行
     7  */
     8 public class Main {
     9     public static void main(String[] args) {
    10         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
    11         DemoService demoService = context.getBean(DemoService.class);
    12         demoService.outputResult();
    13         context.close();
    14     }
    15 }
    运行

    测试

      简介:

        测试是开发工作中不可缺少的部分。单元测试只针对当前开发的类和方法进行测试,可以简单通过模拟依赖来实现,对运行环境没有依赖;但是仅仅进行单元测试是不够的,它只能验证当前类或方法能否正常工作,而我们想要知道系统的各个部分组合在一起是否能正常工作,这就是集成测试存在的意义。

        集成测试一般需要来自不同层的不同对象的交互,如数据库、网络连接、IoC容器等。其实我们也经常通过运行程序,然后通过自己操作来完成类似于集成测试的流程。集成测试为我们提供了一种无须部署或运行程序来完成验证系统各部分是否能正常协同工作的能力。

        Spring通过Spring TestContex Framework对集成测试提供顶级支持。它不依赖于特定的测试框架,既可以用Junit,也可以用TestNG。

      例子:

     1 package com.wisely.highlight_spring4.ch3.fortest;
     2 
     3 /**
     4  * 测试Bean
     5  */
     6 public class TestBean {
     7 
     8     private String content;
     9 
    10     public TestBean(String content) {
    11         super();
    12         this.content = content;
    13     }
    14 
    15     public String getContent() {
    16         return content;
    17     }
    18 
    19     public void setContent(String content) {
    20         this.content = content;
    21     }
    22 }
    测试Bean
     1 package com.wisely.highlight_spring4.ch3.fortest;
     2 
     3 import org.springframework.context.annotation.Bean;
     4 import org.springframework.context.annotation.Configuration;
     5 import org.springframework.context.annotation.Profile;
     6 
     7 /**
     8  * 测试配置类
     9  */
    10 @Configuration
    11 public class TestConfig {
    12 
    13     @Bean
    14     @Profile("dev")
    15     public TestBean devTestBean() {
    16         return new TestBean("from development profile");
    17     }
    18 
    19     @Bean
    20     @Profile("prod")
    21     public TestBean prodTestBean() {
    22         return new TestBean("from production profile");
    23     }
    24 }
    测试配置类
     1 package com.wisely.highlight_spring4.ch3.fortest;
     2 
     3 
     4 import org.junit.Assert;
     5 import org.junit.Test;
     6 import org.junit.runner.RunWith;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.test.context.ActiveProfiles;
     9 import org.springframework.test.context.ContextConfiguration;
    10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    11 
    12 /**
    13  * 测试类
    14  */
    15 @RunWith(SpringJUnit4ClassRunner.class) //SpringJUnit4ClassRunner在JUnit环境下提供Spring TestContext Framework的功能。
    16 @ContextConfiguration(classes = {TestConfig.class}) //@ContextConfiguration用来加载配置ApplicationContext,其中classes属性用来加载配置类。
    17 @ActiveProfiles("prod") //@ActiveProfiles用来声明活动的profile。
    18 public class DemoBeanIntegrationTests {
    19 
    20     @Autowired //可以使用普通的@Autowired注解注入Bean。
    21     private TestBean testBean;
    22 
    23     @Test //测试代码,通过JUnit的Assert来校验结果是否和预期一致。
    24     public void prodBeanShouldInject() {
    25         String expected = "from production profile";
    26         String actual = testBean.getContent();
    27         Assert.assertEquals(expected, actual);
    28     }
    29 }
    测试类

    @Enlable*注解

      简介:

        在Spring中,大量的使用到了@Enlable*注解来开启各种功能,避免了我们自己配置大量的代码,大大降低了使用难度。下面我们来看一下它的实现原理。

        通过观察这些@Enlable*注解的源码,我们发现所有的注解都有一个@Import注解,@Import是用来导入配置类的,这也就意味着这些自动开启的实现其实是导入了一些自动配置的Bean。

        这些导入的配置方式主要分为以下三种类型。

      第一类:

        直接导入配置类。

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.scheduling.annotation;
     7 
     8 import java.lang.annotation.Documented;
     9 import java.lang.annotation.ElementType;
    10 import java.lang.annotation.Retention;
    11 import java.lang.annotation.RetentionPolicy;
    12 import java.lang.annotation.Target;
    13 import org.springframework.context.annotation.Import;
    14 
    15 @Target({ElementType.TYPE})
    16 @Retention(RetentionPolicy.RUNTIME)
    17 @Import({SchedulingConfiguration.class})
    18 @Documented
    19 public @interface EnableScheduling {
    20 }

        直接导入配置类SchedulingConfiguration,这个类注解了@Configuration,且注册了一个scheduledAnnotationProcessor的Bean,源码如下。

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.scheduling.annotation;
     7 
     8 import org.springframework.context.annotation.Bean;
     9 import org.springframework.context.annotation.Configuration;
    10 import org.springframework.context.annotation.Role;
    11 
    12 @Configuration
    13 public class SchedulingConfiguration {
    14     public SchedulingConfiguration() {
    15     }
    16 
    17     @Bean(
    18         name = {"org.springframework.context.annotation.internalScheduledAnnotationProcessor"}
    19     )
    20     @Role(2)
    21     public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
    22         return new ScheduledAnnotationBeanPostProcessor();
    23     }
    24 }

      第二类:

        依据条件选择配置类。

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.scheduling.annotation;
     7 
     8 import java.lang.annotation.Annotation;
     9 import java.lang.annotation.Documented;
    10 import java.lang.annotation.ElementType;
    11 import java.lang.annotation.Retention;
    12 import java.lang.annotation.RetentionPolicy;
    13 import java.lang.annotation.Target;
    14 import org.springframework.context.annotation.AdviceMode;
    15 import org.springframework.context.annotation.Import;
    16 
    17 @Target({ElementType.TYPE})
    18 @Retention(RetentionPolicy.RUNTIME)
    19 @Documented
    20 @Import({AsyncConfigurationSelector.class})
    21 public @interface EnableAsync {
    22     Class<? extends Annotation> annotation() default Annotation.class;
    23 
    24     boolean proxyTargetClass() default false;
    25 
    26     AdviceMode mode() default AdviceMode.PROXY;
    27 
    28     int order() default 2147483647;
    29 }

        AsyncConfigurationSelector通过条件来选择需要导入的配置类,AsyncConfigurationSelector的根接口为ImportSelector,这个接口需重写selectImports方法,在此方法中进行事先条件判断。

        下面的源码中,若adviceMode为PORXY,则返回ProxyAsyncConfiguration这个配置类,若activeMode为ASPECTJ,则返回AspectJAsyncConfiguration配置类。

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.scheduling.annotation;
     7 
     8 import org.springframework.context.annotation.AdviceMode;
     9 import org.springframework.context.annotation.AdviceModeImportSelector;
    10 
    11 public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
    12     private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME = "org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
    13 
    14     public AsyncConfigurationSelector() {
    15     }
    16 
    17     public String[] selectImports(AdviceMode adviceMode) {
    18         switch(adviceMode) {
    19         case PROXY:
    20             return new String[]{ProxyAsyncConfiguration.class.getName()};
    21         case ASPECTJ:
    22             return new String[]{"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration"};
    23         default:
    24             return null;
    25         }
    26     }
    27 }

      第三类:

        动态注册Bean。

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.context.annotation;
     7 
     8 import java.lang.annotation.Documented;
     9 import java.lang.annotation.ElementType;
    10 import java.lang.annotation.Retention;
    11 import java.lang.annotation.RetentionPolicy;
    12 import java.lang.annotation.Target;
    13 
    14 @Target({ElementType.TYPE})
    15 @Retention(RetentionPolicy.RUNTIME)
    16 @Documented
    17 @Import({AspectJAutoProxyRegistrar.class})
    18 public @interface EnableAspectJAutoProxy {
    19     boolean proxyTargetClass() default false;
    20 }

        AspectJAutoProxyRegistrar实现了ImportBeanDefinitionRegistrar接口,ImportBeanDefinitionRegistrar的作用是在运行时自动添加Bean到已有的配置类,通过重写方法:

     public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) 。

        其中,AnnotationMetadata参数用来获得当前配置类上的注解,BeanDefinitionRegistry参数用来注册Bean。源码如下:

     1 //
     2 // Source code recreated from a .class file by IntelliJ IDEA
     3 // (powered by Fernflower decompiler)
     4 //
     5 
     6 package org.springframework.context.annotation;
     7 
     8 import org.springframework.aop.config.AopConfigUtils;
     9 import org.springframework.beans.factory.support.BeanDefinitionRegistry;
    10 import org.springframework.core.annotation.AnnotationAttributes;
    11 import org.springframework.core.type.AnnotationMetadata;
    12 
    13 class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
    14     AspectJAutoProxyRegistrar() {
    15     }
    16 
    17     public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    18         AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
    19         AnnotationAttributes enableAJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
    20         if (enableAJAutoProxy.getBoolean("proxyTargetClass")) {
    21             AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
    22         }
    23 
    24     }
    25 }
  • 相关阅读:
    python入学代码
    python安装和pycharm安装与笔记
    python预习day1
    python-tyoira基本
    Typora基础
    学习一下saltstack 服务器批量管理
    消息队列与kafka
    消息队列rabbitmq
    redis数据库在linux上的学习
    蓝绿部署、滚动发布、灰度发布的介绍以及最佳实践
  • 原文地址:https://www.cnblogs.com/gaofei-1/p/8765372.html
Copyright © 2011-2022 走看看