25、自动装配[email protected]根据环境注册bean

25、自动装配[email protected]根据环境注册bean

  • 指定组件在哪个环境的情况下才能被注册到容器中
  • 加了环境标识的,只有这个环境被激活才能注册到组件中
  • 默认是default环境
  • 写在类上,整个配置类的激活的时候才能生效
  • 没有标注环境标识的bean,在任何环境下都是加载的
package org.springframework.context.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.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Profiles;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {

    /**
     * 指定组件在哪个环境的情况下才能被注册到容器中
     * The set of profiles for which the annotated component should be registered.
     */
    String[] value();

}

25.1 实现

package com.hw.springannotation.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @Description Profile
 * @Author hw
 * @Date 2018/11/29 19:25
 * @Version 1.0
 */
@Component
@PropertySource(value = {"classpath:/datasource.properties"})
public class MainConfigOfProfile implements EmbeddedValueResolverAware {

    @Value("${db.username}")
    private String username;

    private String driveClassName;

    private StringValueResolver resolver;

    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.resolver = resolver;
        this.driveClassName = this.resolver.resolveStringValue("${db.driveClassName}");
    }

    @Profile("default")
    @Bean
    public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClass(driveClassName);
        return dataSource;
    }

    @Profile("dev")
    @Bean
    public DataSource dataSourceDev(@Value("${db.password}") String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mysql");
        dataSource.setDriverClass(driveClassName);
        return dataSource;
    }

    @Profile("prod")
    @Bean
    public DataSource dataSourceProd(@Value("${db.password}") String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/qm_dmp");
        dataSource.setDriverClass(driveClassName);
        return dataSource;
    }
}

运行:

25.2 切换环境-使用命令行动态参数

  • 在运行时指定
-Dspring.profiles.active=prod

25.3 切换环境-使用代码的方式

  • 之前使用的是有参构造器,配置加载完,容器就刷新了,所以使用无参构造器
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
        this();
        register(annotatedClasses);
        refresh();
    }

步骤

  1. 构造IOC容器
  2. 设置需要激活的环境
  3. 注入配置类
  4. 启动刷新容器
@Test
public void test() {
    // 1. 构造IOC容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    // 2. 设置需要激活的环境(可以同时激活多个)
    applicationContext.getEnvironment().setActiveProfiles("test", "dev");
    // 3. 注入配置类
    applicationContext.register(MainConfigOfProfile.class);
    // 4. 启动刷新容器
    applicationContext.refresh();

    String[] definitionNames = applicationContext.getBeanDefinitionNames();
    for (String name : definitionNames) {
        System.out.println(name);
    }

}

原文地址:https://www.cnblogs.com/Grand-Jon/p/10046323.html

时间: 2024-08-10 12:59:21

25、自动装配[email protected]根据环境注册bean的相关文章

24、自动装配[email&#160;protected]环境搭建

24.自动装配[email protected]环境搭建 Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能. 开发环境.测试环境.正式环境 数据源切换 24.1 添加 数据源和jdbc驱动 pom 依赖 <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifac

21、自动装配[email&#160;protected]&amp;@Inject

21.自动装配[email protected]&@Inject Spring 还支持使用@Resource(JSR250)和@Inject(JSR330)[Java规范的注解] AutowiredAnnotationBeanPostProcessor 完成解析自动装配功能 21.1 @Resource 可以和@Autowired一样实现自动注入功能,默认是按照组件名称进行装配的. 没有能支持@Primary功能,没有支持@Autowired(required = false) 21.2 @In

从头认识Spring-2.3 注解装配[email&#160;protected](3)-通过构造器方法注入

这一章节我们来讨论一下注解装配的@autowired是怎样通过set方法或者其他方法注入? 1.domain 蛋糕类:(不变) package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_8; public class Cake { private String name = ""; public String getName() { return name; } public void setName(String name

从头认识Spring-2.4 基于java的标准注解装配[email&#160;protected](2)-通过set方法或者其它方法注入

这一章节我们来讨论一下基于java的标准注解装配标签@Inject是如何通过通过set方法或者其它方法注入? 在使用@Inject标签之前.我们须要在pom文件中面增加以下的代码: <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>

从头认识Spring-2.4 基于java的标准注解装配[email&#160;protected]限定器@Named

这一章节我们来讨论一下基于java的标准注解装配标签@Inject的限定器@Named. 1.domain 蛋糕类: package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_16; import javax.inject.Named; @Named("myCake") public class Cake { private String name = ""; public String getName(

从头认识Spring-2.4 基于java的标准注解装配[email&#160;protected](3)-通过构造器方法注入

这一章节我们来讨论一下基于java的标准注解装配标签@Inject是怎样通过通过构造器方法注入? 在使用@Inject标签之前,我们需要在pom文件里面加入下面的代码: <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> 上面是j

从头认识Spring-2.3 注解装配[email&#160;protected](4)-required(1)

这一章节我们来详细讨论一下@autowired里面的参数required. 1.domain(重点) 蛋糕类: package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_9; public class Cake { private String name = ""; public String getName() { return name; } public void setName(String name) { this

从头认识Spring-2.3 注解装配[email&#160;protected](5)-限定器@Qualifier(1)

这一章节我们来具体讨论一下配合@autowired一起使用的限定器@Qualifier. 1.domain(重点) 蛋糕类: package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_11; public class Cake { private String name = ""; public String getName() { return name; } public void setName(String name

尚硅谷springboot学习[email&#160;protected],@ImportResource,@Bean

@PropertySource 使用指定的属性文件而不一定是application.xxx 同样可以注入相关内容 @ImportResource 导入Spring的配置文件,让配置文件里面的内容生效: Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别: 想让Spring的配置文件生效,加载进来:@ImportResource标注在一个配置类上 @Bean SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式 package com.at