Spring5.0源码深度解析之理解Configuration注解

Stella981
• 阅读 556

Spring5.0源码深度解析之理解Configuration注解

Spring5.0之:@Configuration的使用

@Configuration用于定义配置类,可替换XML配置文件,被注解的类内部包含有一个或者多个被**@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或者AnnotationConfigWebApplicationContext**类进行扫描,并用于构建Bean定义,初始化Spring容器。

@Configuration public class MySpringConfig { @Bean public UserEntity userEntity() { return new UserEntity("xuyu", 21); } }

AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MySpringConfig.class);

一、用@Configuration加载spring

1.1、@Configuration配置spring并启动spring容器
1.2、@Configuration启动容器+@Bean注册Bean
1.3、@Configuration启动容器+@Component注册Bean
1.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类的

二、组合多个配置类

2.1、在@configuration中引入其它注解配置
2.2、@configuration嵌套

三、@EnableXXX注解
四、@Profile逻辑组配置
五、使用外部变量


一、@Configuation加载Spring方法

1.1、@Configuration配置spring并启动spring容器

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)

@Configuration public class TestConfiguration { public TestConfiguration() { System.out.println("TestConfiguration容器启动初始化。。。"); } }

相当于:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>

主方法进行测试:

public class TestMain { public static void main(String[] args) {

    // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
    ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

    // 如果加载spring-context.xml文件:
    // ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
}

}

从运行主方法结果可以看出,spring容器已经启动了:

Spring5.0源码深度解析之理解Configuration注解

1.2、@Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期

@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的<bean>,作用为:注册bean对象

bean类:

public class TestBean {

    private String username;
    private String url;
    private String password;

    public void sayHello() {
        System.out.println("TestBean sayHello...");
    }

    public String toString() {
        return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
    }

    public void start() {
        System.out.println("TestBean 初始化。。。");
    }

    public void cleanUp() {
        System.out.println("TestBean 销毁。。。");
    }
}

配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }

    // @Bean注解注册bean,同时可以指定初始化和销毁方法
    // @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp")
    @Bean
    @Scope("prototype")
    public TestBean testBean() {
        return new TestBean();
    }
}

主方法测试类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
    public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

        // 如果加载spring-context.xml文件:
        // ApplicationContext context = new
        // ClassPathXmlApplicationContext("spring-context.xml");
        
         //获取bean
        TestBean tb = (TestBean) context.getBean("testBean");
        tb.sayHello();
    }
}

结果:

Spring5.0源码深度解析之理解Configuration注解

注: 

(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 
(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 
(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

@Bean下管理bean的生命周期

可以使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器便可调用生命周期方法。

生命周期方法也称为回调方法,因为它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注释。如果您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。

以下代码显示了在 XML 配置中通常使用 bean 元素定义回调的方法。

package com.mayikt.v1.entity;

public class TestBean {

    public void sayHello() {
        System.out.println("TestBean sayHello...");
    }
    public void start() {
        System.out.println("TestBean 初始化。。。");
    }
    public void cleanUp() {
        System.out.println("TestBean 销毁。。。");
    }
}

@Configuration
@ComponentScan(basePackages = "com.mayikt.v1.entity")
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }

    //@Bean注解注册bean,同时可以指定初始化和销毁方法
    @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp")
    @Scope("prototype")
    public TestBean testBean() {
        return new TestBean();
    }
}

public class TestMain {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
        TestBean tb = (TestBean) context.getBean("testBean");
        tb.sayHello();
        System.out.println(tb);

        TestBean tb2 = (TestBean) context.getBean("testBean");
        tb2.sayHello();
        System.out.println(tb2);
    }
}

Spring5.0源码深度解析之理解Configuration注解

分析:

结果中的1:表明initMethod生效

结果中的2:表明@Scope("prototype")生效

1.3、@Configuration启动容器+@Component注册Bean

//添加注册bean的注解
@Component
public class TestBean {

    private String username;
    private String url;
    private String password;

    public void sayHello() {
        System.out.println("TestBean sayHello...");
    }
    public String toString() {
        return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
    }
    public void start() {
        System.out.println("TestBean 初始化。。。");
    }
    public void cleanUp() {
        System.out.println("TestBean 销毁。。。");
    }
}

@Configuration
//添加自动扫描注解,basePackages为TestBean包路径
@ComponentScan(basePackages = "com.mayikt.v1.entity")
public class TestConfiguration {
    public TestConfiguration() {
        System.out.println("TestConfiguration容器启动初始化。。。");
    }
}

public class TestMain {
    public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
        // 如果加载spring-context.xml文件:
        // ApplicationContext context = new
        // ClassPathXmlApplicationContext("spring-context.xml");
        //获取bean
       TestBean tb = (TestBean) context.getBean("testBean");
        tb.sayHello();
    }
}

Spring5.0源码深度解析之理解Configuration注解

1.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类

AnnotationConfigApplicationContext 的register 方法传入配置类来注册配置类

public class TestMain {
    public static void main(String[] args) {
        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext();
        ((AnnotationConfigApplicationContext) context).register(TestConfiguration.class);
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (int i = 0; i < beanDefinitionNames.length; i++) {
            System.out.println(beanDefinitionNames[i]);
        }
    }
}

Spring5.0源码深度解析之理解Configuration注解

1.5、@Configuation总结

 @Configuation等价于

 @Bean等价于

 @ComponentScan等价于<context:component-scan base-package="com.xxx"/>

二、组合多个配置类

2.1、在@configuration中引入其它注解配置

@Configuration @Import(TestConfiguration.class) public class WebConfig { }

@Configuration @ComponentScan(basePackages = "com.mayikt.v1.entity") public class TestConfiguration { public TestConfiguration() { System.out.println("TestConfiguration容器启动初始化。。。"); }

//@Bean注解注册bean,同时可以指定初始化和销毁方法
@Bean(name="testBean2",initMethod="start",destroyMethod="cleanUp")
@Scope("prototype")
public TestBean2 testBean2() {
    return new TestBean2();
}

}

public class TestMain2 { public static void main(String[] args) {

    // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
    ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
    // 获取bean
    TestBean2 tb2 = (TestBean2) context.getBean("testBean2");
    tb2.sayHello();

    TestBean tb = (TestBean) context.getBean("testBean");
    tb.sayHello();
}

}

结果:

Spring5.0源码深度解析之理解Configuration注解

2.2、@configuration嵌套

@Configuration public class MySpringConfig { @Configuration static class entity{ @Bean UserEntity userEntity(){ return new UserEntity("mayikt", 21); } } /*@Bean public UserEntity userEntity() { return new UserEntity("xuyu", 21); }*/ }

public class V2TestSpring { private static AnnotationConfigApplicationContext annotationConfigApplicationContext;

public static void main(String\[\] args) {
    annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MySpringConfig.class);
    System.out.println("启动配置加载完毕...");
    UserEntity userEntity = annotationConfigApplicationContext.getBean("userEntity", UserEntity.class);
    String\[\] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
    for (int i = 0; i < beanDefinitionNames.length; i++) {
        System.out.println(beanDefinitionNames\[i\]);
    }
}

}

结果

Spring5.0源码深度解析之理解Configuration注解

3、@EnableXXX注解

配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。

@EnableAspectJAutoProxy---《spring AOP 之:@Aspect注解

@EnableScheduling--《Spring 3.1新特性之二:@Enable*注解的源码,spring源码分析之定时任务Scheduled注解

4、@Profile逻辑组配置

见《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用

5、使用外部变量

1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value

见《Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用

思考问题:springbean对象在什么时候创建的?

答案:默认情况下是非懒加载的。

@Lazy

  • Lazy表示为懒加载,当真正需要引用获取的时候才会被加载
  • True 表示为非懒加载 false表示为在IOC容器加载的时候被创建
@Service
@Lazy(true)
public class UserService {
    public UserService() {
        System.out.println("UserService无参数构造被加载...");
    }
}

本文参考

蚂蚁课堂:http://www.mayikt.com/

参考博客:https://www.cnblogs.com/duanxz/p/7493276.html

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
springboot源码分析
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Stella981 Stella981
2年前
Spring5.0源码深度解析之Spring核心注解
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Stella981 Stella981
2年前
Spring5.0源码深度解析之SpringBean的Aop的使用
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Stella981 Stella981
2年前
Spring5.0源码深度解析之SpringBean的Aop源码分析
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)SpringAop源码分析
Stella981 Stella981
2年前
Spring5.0源码深度解析之SpringBean声明事务底层实现原理
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Stella981 Stella981
2年前
Spring5.0源码深度解析之SpringBean循环依赖问题解决方案
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Stella981 Stella981
2年前
Spring5.0源码深度解析之SpringBean的生命周期
!(https://gss1.bdstatic.com/vo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign0c730b84bd19ebc4c078719fba1da8c1/37d12f2eb9389b503a80d4b38b35e5dde6116ed7.jpg)
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这