【Spring】Spring高级话题-@Enable***注解的工作原理-程序员宅基地

技术标签: python  java  测试  

转载请注明出处:http://blog.csdn.net/qq_26525215

本文源自大学之旅_谙忆的博客

@EnableAspectJAutoProxy

@EnableAspectJAutoProxy注解 激活Aspect自动代理

 <aop:aspectj-autoproxy/>
  • 1

开启对AspectJ自动代理的支持。

在用到AOP的自动代理的时候用,如果你理解了Java的动态代理,很容易的就会熟悉AOP的自动代理的。

@EnableAsync

@EnableAsync注解开启异步方法的支持。 
这个相信大家都比较熟悉的。对于异步应该都理解的。 
不太熟悉的,可以看这篇博客:-有示例 
【Spring】Spring高级话题-多线程-TaskExecutor

@EnableScheduling

@EnableScheduling注解开启计划任务的支持。

也就是字面上的意思,开启计划任务的支持! 
一般都需要@Scheduled注解的配合。

详情见此博客: 
【Spring】Spring高级话题-计划任务-@EnableScheduling

@EnableWebMVC

@EnableWebMVC注解用来开启Web MVC的配置支持。

也就是写Spring MVC时的时候会用到。

@EnableConfigurationProperties

@EnableConfigurationProperties注解是用来开启对@ConfigurationProperties注解配置Bean的支持。

也就是@EnableConfigurationProperties注解告诉Spring Boot 使能支持@ConfigurationProperties

@EnableJpaRepositories

@EnableJpaRepositories注解开启对Spring Data JPA Repostory的支持。

Spring Data JPA 框架,主要针对的就是 Spring 唯一没有简化到的业务逻辑代码,至此,开发者连仅剩的实现持久层业务逻辑的工作都省了,唯一要做的,就只是声明持久层的接口,其他都交给 Spring Data JPA 来帮你完成!

简单的说,Spring Data JPA是用来持久化数据的框架。

@EnableTransactionManagement

@EnableTransactionManagement注解开启注解式事务的支持。

注解@EnableTransactionManagement通知Spring,@Transactional注解的类被事务的切面包围。这样@Transactional就可以使用了。

@EnableCaching

@EnableCaching注解开启注解式的缓存支持

通过这些简单的@Enable*可以开启一项功能的支持,从而避免自己配置大量的代码,很大程度上降低了使用难度。

我们一起来观察下这些@Enable*注解的源码,可以发现所有的注解都有一个@Import注解。

@Import注解是用来导入配置类的,这也就是说这些自动开启的实现其实是导入了一些自动配置的Bean。

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

@Import注解导入配置方式的三种类型

第一类:直接导入配置类

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.SchedulingConfiguration;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({SchedulingConfiguration.class})
@Documented
public @interface EnableScheduling {
}

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

/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.scheduling.annotation;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.scheduling.config.TaskManagementConfigUtils;

/**
 * {@code @Configuration} class that registers a {@link ScheduledAnnotationBeanPostProcessor}
 * bean capable of processing Spring's @{@link Scheduled} annotation.
 *
 * <p>This configuration class is automatically imported when using the
 * @{@link EnableScheduling} annotation. See {@code @EnableScheduling}'s javadoc
 * for complete usage details.
 *
 * @author Chris Beams
 * @since 3.1
 * @see EnableScheduling
 * @see ScheduledAnnotationBeanPostProcessor
 */
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class SchedulingConfiguration {

    @Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }

}

第二类:依据条件选择配置类

EnableAsync 注解核心代码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {
    Class<? extends Annotation> annotation() default Annotation.class;
    boolean proxyTargetClass() default false;
    AdviceMode mode() default AdviceMode.PROXY;
    int order() default Ordered.LOWEST_PRECEDENCE;

}

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

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

public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {

    private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
            "org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";

    /**
     * {@inheritDoc}
     * @return {@link ProxyAsyncConfiguration} or {@code AspectJAsyncConfiguration} for
     * {@code PROXY} and {@code ASPECTJ} values of {@link EnableAsync#mode()}, respectively
     */
    @Override
    public String[] selectImports(AdviceMode adviceMode) {
        switch (adviceMode) {
            case PROXY:
                return new String[] { ProxyAsyncConfiguration.class.getName() };
            case ASPECTJ:
                return new String[] { ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME };
            default:
                return null;
        }
    }

}

第三类:动态注册Bean

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
    boolean proxyTargetClass() default false;
}

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

@Override
    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)

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

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * Register, escalate, and configure the AspectJ auto proxy creator based on the value
     * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
     * {@code @Configuration} class.
     */
    @Override
    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

        AnnotationAttributes enableAJAutoProxy =
                AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
        if (enableAJAutoProxy.getBoolean("proxyTargetClass")) {
            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
        }
    }

}

本文章由[谙忆]编写, 所有权利保留。

转载请注明出处:http://blog.csdn.net/qq_26525215

本文源自大学之旅_谙忆的博客

转载于:https://my.oschina.net/u/3714931/blog/1593147

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34029680/article/details/92402857

智能推荐

WIndows下使用Qemu安装Arm版Kylin系统_qemu_kylin_efi.fd-程序员宅基地

文章浏览阅读8.7k次,点赞10次,收藏51次。提示:转载请注明出处文章目录前言一、Qemu是什么?二、操作步骤1.环境准备(1).qemu安装(2).QEMU_EFI.fd:镜像启动时的BIOS。(3).ARM系统的.iso镜像:(4).制作镜像(5).准备目录2.安装虚拟机3.启动虚拟机总结问题描述:前言随着国产化的浪潮一步一步的加大,我们接触的国产系统和国产硬件也在不断的增多,忍不住的吐槽,现在的硬件是真的倒退了好多年,而且也特别的贵,但是为支持国产,我们也需要更多的进行国产化的适配和学习,linux下搭建比较简单,windows则比较复_qemu_kylin_efi.fd

OneNote 找回误删除笔记_onenote已删除的笔记-程序员宅基地

文章浏览阅读6k次。真的OneNote的这个设计差点没吓死我,还好最终找到了。百度很多方法都不好使。1.去OneNote online 就是web端的OneNote2.点击告诉我们你要做什么3.点击已删除页面这样就找到了,实测iPad端删除这里能找回..._onenote已删除的笔记

Umi2.x升级到Umi3.x_node 多少版本对应的umi3-程序员宅基地

文章浏览阅读6.9k次,点赞5次,收藏7次。Umi3.x升级版本之路(一)修改依赖扁平化配置import all from umi修正语法支持antd4.x修改依赖npm uninstall -S dva antdnpm uninstall -D umi-plugin-react npm install -D umi@3 @umijs/preset-react// package.json"engines": { "node": ">=10.13.0"}// tsconfig.json"paths": { "@/*":_node 多少版本对应的umi3

【论文阅读】【三维目标检测】在Range view上做3D目标检测_rangeview-程序员宅基地

文章浏览阅读3.3k次,点赞10次,收藏22次。文章目录BEV or Range ViewRangeDet: In Defense of Range View for LiDAR-based 3D Object DetectionRange Conditioned Pyramid InMeta-Kernel ConvolutionWeighted Non-Maximum SuppressionData Augmentation in Range View DataExperimentrange view是仅针对物理旋转式扫描的激光雷达的特殊view,例_rangeview

shell 实现并发,并控制并发数量_shell 并发-程序员宅基地

文章浏览阅读4k次,点赞4次,收藏26次。为了方便理解,一步步的来首先先看一下串行的:#! /bin/bashST=$(date +%s)for i in $(seq 1 10)do echo $i sleep 1 # 模拟程序、命令doneET=$(date +%s)TIME=$(( ${ET} - ${ST} ))echo "time: ${TIME}"输出结果:12345678910time: 10这就最原始的进程运行模拟,串行方式,无法有效利用计算机的资源,_shell 并发

Mybatis-puls自动分页Page无法分页解决_使用mybatis-plus中page进行分页不生效-程序员宅基地

文章浏览阅读3.3k次,点赞3次,收藏5次。一开始使用Page时发现数据能出来但是无法分页,只能全部显示。打印数据出来也显示0。最后查了许多资料发现这个插件需要一个工具类的支持才可以实现。检查了一下代码发现也没有问题。最后更改完成测试,好使了。_使用mybatis-plus中page进行分页不生效

随便推点

AS5045磁旋转编码器使用以及STM32接收学习心得(另modbus协议、RS485接口、RS485转TTL说明)-程序员宅基地

文章浏览阅读5.2k次,点赞8次,收藏40次。一、电气接口1、5V供电,1:VDD5;2:A;3: B;4:GND2、板子上没有配终端电阻,需要自己根据应用需要配电阻3、板子外径30mm,安装孔内径2.7mm,可配2.5的螺钉,两孔中心间距21mm.二、RS485接口通信协议编码器485波特率范围:1200-57600,可以根据具体实际请款设置波特率,默认设率9600,8,n,1。三、modbus通信协议格式(1)、moubus协议概要1、Modbus协议是一种单主/多从的通信协议,其特点是在同一时间,总线上只能有一个主设备,但可以_rs485转ttl

在阿里云CentOS7上搭建ftp服务器_阿里云centos配置ftp-程序员宅基地

文章浏览阅读3.5k次。当我再次被各种出站入站规则玩弄,在搜索引擎的帮助走出泥淖后,我决定记下这次经历_阿里云centos配置ftp

ARM Linux 3.x的设备树(Device Tree)-程序员宅基地

文章浏览阅读102次。2019独角兽企业重金招聘Python工程师标准>>> ..._error: include/dt-bindings/power/xlnx-zynqmp-power.h

使用JavaScript制作动态网页-2_javascript实现同个窗口的动态网页-程序员宅基地

文章浏览阅读1.8k次,点赞2次,收藏15次。使用JavaScript制作动态网页-2表单验证<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>表单验证</title></head><body> <form action="..._javascript实现同个窗口的动态网页

Ubuntu20.04解决应用中心打不开的问题_snap商店打不开-程序员宅基地

文章浏览阅读1.5w次,点赞9次,收藏76次。Ubuntu20.04软件中心打不开 尝试了很多方法 Ubuntu 20.04 默认把软件中心换成了 snap, 感觉 snap 应用老出状况, snap 应用不但体积大, 安装好的应用还不时就崩溃, 所以如果要把电脑里的所有 snap 应用全部替换了, snapd 也卸载了. 下面这三句可以有效的解决 sudo apt install ubuntu-software sudo sn..._snap商店打不开

C语言-数据结构-栈-实验报告_数据结构栈的应用实验报告-程序员宅基地

文章浏览阅读6.5k次,点赞8次,收藏70次。实验报告内容:一、实验目的、要求:(1)熟练掌握栈的特点(先进后出FILO)及基本操作,如入栈、出栈等,栈的顺序存储结构和链式存储结构,以便在实际问题背景下灵活应用。(2)编写适当的主函数和相关函数,使实验题目运行出正确结果。(3)当场编程、调试、编译。(4)程序具有一定的健壮性、可读性,尽量简洁。(5)程序运行完成后分别存盘,上交实验报告,要求写出实验体会二、实验内容:(1)实验题目(2)主要函数的算法设计思想(3)程序清单(3)测试数据、实验结果及结论(4)实验体会(实验中存在的_数据结构栈的应用实验报告