系列二十二、各种注解

本文详细解读了SpringBoot中的重要配置注解如@Import用于导入Bean,@Configuration替代XML配置,@SpringBootApplication的复合注解,以及@LoadBalanced和@EnableDiscoveryClient在分布式系统中的应用。讨论了加@Configuration注解的配置类如何影响bean的生命周期和互调行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、@Import

# 用法

1)@Import(User.class):如果导入的是配置类,将会按照配置类正常解析,如果是个普通类就会解析成bean
2)@Import(实现了ImportSelector接口的类.class):可以一次性注册多个bean,返回一个String[],每一个值就是类的完整类路劲
3)@Import(MyImportBeanDefinitionRegistrar.class):可以一次性注册多个bean,通过BeanDefinitionRegistry来动态注册BeanDefinition
4)@Import(MyDeferredImportSelector.class)

二、@Configuration

2.1、概述

@Configuration是用来代替传统的xml的配置方式配置bean的。

2.2、不加就不能配置bean吗

答:能。 

2.2.1、ComponentA

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/27 15:45
 * @Description:
 */
public class ComponentA {

    public ComponentA componentA() {
        System.out.println("ComponentA's NoArgsConstructor was invoked!");
        return new ComponentA();
    }

}

2.2.2、MySpringConfig

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/27 15:45
 * @Description:
 */
@Slf4j
public class MySpringConfig {

    @Bean
    public ComponentA componentA() {
        return new ComponentA();
    }

}

2.2.3、SpringConfigurationMainApp

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/27 15:46
 * @Description:
 */
@Slf4j
public class SpringConfigurationMainApp {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class);
        ComponentA componentA = context.getBean("componentA", ComponentA.class);
        log.info("componentA:{}",componentA);
    }

}

2.3、加与不加的区别

        配置类加了@Configuration注解,Spring会为配置类创建cglib动态代理,@Bean方法的调用就会通过容器getBean进行获取,保证当@Bean方法进行互调时,@Bean是单例的。

2.4、不加@Configuration注解案例

2.4.1、ComponentA(同2.2.1)

2.4.2、ComponentB

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/27 15:45
 * @Description:
 */
public class ComponentB {

    public ComponentB componentB() {
        System.out.println("ComponentB's NoArgsConstructor was invoked!");
        return new ComponentB();
    }

}

2.4.3、MySpringConfig

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/27 15:45
 * @Description:
 */
//@Configuration
@Slf4j
public class MySpringConfig {

    @Bean
    public ComponentA componentA() {
        ComponentB componentB1 = componentB();
        ComponentB componentB2 = componentB();
        log.info("componentB1:{},componentB2:{},(componentB1 == componentB2) ? {}",componentB1,componentB2,(componentB1 == componentB2));
        return new ComponentA();
    }

    @Bean
    public ComponentB componentB() {
        return new ComponentB();
    }

}

2.4.4、SpringConfigurationMainApp(同上)

2.5、加@Configuration注解案例

代码同2.4,但是要在MySpringConfig上标注@Configuration注解。

2.6、结论

        虽然配置类上加与不加@Configuration注解都可以创建bean,但是当@Bean方法内部调用另一个@Bean标注的方法时,如果配置类没有加@Configuration注解,那么Spring将不会为其创建Cglib动态代理,而是将被调用的@Bean方法当做一个普通方法,于是就出现了2.4中的结果。

2.7、原理

        1、启动IOC容器的时候会注册一个解析配置的处理器 ConfigurationClassPostProcessor

        2、调用invokeBeanFactoryPostProcessors(beanFactory)时,就会去调用postProcessBeanDefinitionRegistry进行解析配置(解析加了@Configuration、@Component、@Import、@Bean的类,目的是为了注册BeanDefinition)
        3、ConfigurationClassPostProcessor.postProcessBeanFactory去创建cglib动态代理;

        4、当@Bean方法进行互调时,会通过cglib进行增强,通过调用的方法名作为bean的名称去IOC容器中获取,进而保证了@Bean方法的单例

三、@SpringBootApplication

3.1、概述

        @SpringBootApplication是SpringBoot中的注解,通常标识在主启动类上,表明当前应用是一个SpringBoot工程,它实际上是一个复合注解,结构如下:

四、@SpringBootConfiguration

4.1、概述

        @SpringBootConfiguration也是SpringBoot中的注解,实际上就是一个@Configuration,表示启动类也是一个配置类,结构如下:

五、@EnableAutoConfiguration

5.1、概述

        @EnableAutoConfiguration也是SpringBoot中的注解,它导入了一个AutoConfigurationImportSelector,用于加载classpath/META-INF/spring.factories中所定义的所有自动配置类,并将这些自定配置类注册为bean,结构如下:

六、@Conditional

6.1、概述

        @Conditional注解是Spring中的一个注解,主要用于xxxAutoConfiguration类中,用于程序员自定义starter时进行扩展,这些自动配置类在IOC容器加载过程中最后才被加载,其中起到关键作用的注解就是@ConditionalXxx,例如:@ConditionalOnMissingClass({"org.aspectj.weaver.Advice"})、@ConditionalOnClass({Advice.class})、@ConditionalOnProperty()...等等,结构如下:

七、参数校验相关注解 

空检查
@Null            验证对象是否为null
@NotNull        验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank        检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty        检查约束元素是否为NULL或者是EMPTY. 
 
Booelan检查
@AssertTrue        验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
 
长度检查
@Size(min=, max=)        验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=)        验证注解的元素值长度在min和max区间内
 
日期检查
@Past        验证 Date 和 Calendar 对象是否在当前时间之前  
@Future        验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则
 
数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min            验证 Number 和 String 对象是否大等于指定的值  
@Max            验证 Number 和 String 对象是否小等于指定的值  
@DecimalMax        被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin        被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits            验证 Number 和 String 的构成是否合法  
@Digits(integer=,fraction=)        验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
 
@Range(min=, max=)    验证注解的元素值在最小值和最大值之间
@Range(min=10000,max=50000,message="range.bean.wage")
 
@Valid 写在方法参数前,递归的对该对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email  验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)

八、@LoadBalanced

8.1、概述

        @LoadBalanced注解是Spring Cloud提供的一个注解,通常结合RestTemplate一起使用。源码如下:

8.2、案例

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/12/29 16:43
 * @Description:
 */
@Configuration
public class MyApplicationContextConfig {

    /**
     * @LoadBalanced : 使用@LoadBalanced注解,赋予RestTemplate负载均衡的能力
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

九、@EnableDiscoveryClient

9.1、概述

        @EnableDiscoveryClient注解是Spring Cloud提供的一个注解,用于向使用consul或者zookeeper作为注册中心时注册服务,源码如下:

9.2、案例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值