Spring注解开发——25、自动装配-@Profile根据环境注册bean

目录

25、自动装配-@Profile根据环境注册bean

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

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

步骤


25、自动装配-@Profile根据环境注册bean

  • 指定组件在哪个环境的情况下才能被注册到容器中
  • 加了环境标识的,只有这个环境被激活才能注册到组件中
  1.  切换环境-使用命令行动态参数:     -Dspring.profiles.active=prod
  2. 使用代码的方式:之前使用的是有参构造器,配置加载完,容器就刷新了,所以使用无参构造器

  • 默认是default环境
  • 写在类上,整个配置类的激活的时候才能生效
  • 没有标注环境标识的bean,在任何环境下都是加载的

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

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

代码:

package com.suirui.springanno.autowiredDemo.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.suirui.springanno.autowiredDemo.entity.Red;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

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

@Configuration
@PropertySource(value = {"classpath:/db.properties","classpath:/person.properties"})
public class MainConfigAutoWired2 implements EmbeddedValueResolverAware {

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

    //通过EmbeddedValueResolverAware获取Spring值解析器,然后再去获取properties中的数据
    StringValueResolver stringValueResolver;

    //测试数据源
    @Bean("dataSourceTest")
//    @Profile("default")
    @Profile("test")
    public DataSource dataSourceTest(@Value("${db.username}" )String pwd ) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");

        String driver = stringValueResolver.resolveStringValue("${db.driveClassName}");
        dataSource.setDriverClass(driver);
        return dataSource;
    }

    //开发数据源
    @Bean("dataSourceDev")
    @Profile("dev")
    public DataSource dataSourceDev(@Value("${db.username}" )String pwd ) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
        String driver = stringValueResolver.resolveStringValue("${db.driveClassName}");
        dataSource.setDriverClass(driver);
        return dataSource;
    }

    //生产环境
    @Bean("dataSourceProd")
    @Profile("prod")
    public DataSource dataSourceProd(@Value("${db.username}" )String pwd ) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/prod");
        String driver = stringValueResolver.resolveStringValue("${db.driveClassName}");
        dataSource.setDriverClass(driver);
        return dataSource;
    }


    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        this.stringValueResolver = stringValueResolver;

    }
}


package com.suirui.springanno.autowiredDemo;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.suirui.springanno.autowiredDemo.config.MainConfigAutoWired;
import com.suirui.springanno.autowiredDemo.config.MainConfigAutoWired2;
import com.suirui.springanno.autowiredDemo.entity.Red;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.util.Map;

public class MainTestAutoWired2 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfigAutoWired2.class);

        String[] beanNamesForType = ac.getBeanNamesForType(DataSource.class);
        for (String s : beanNamesForType) {
            System.out.println(s);
        }
        Map beansOfType = ac.getBeansOfType(DataSource.class);
        for (Map.Entry entry : beansOfType.entrySet()) {
            System.out.println(entry.getKey());
            ComboPooledDataSource ds = (ComboPooledDataSource) entry.getValue();
            String user = ds.getUser();
            String password = ds.getPassword();
            String driverClass = ds.getDriverClass();
            System.out.println("user: " + user + ",pwd: "+ password + ". driverClass: " + driverClass);
            System.out.println("");
        }


    }
}

Spring注解开发——25、自动装配-@Profile根据环境注册bean_第1张图片

25.3 切换环境-使用代码的方式(覆盖命令行方式)

  • 之前使用的是有参构造器,配置加载完,容器就刷新了,所以使用无参构造器

步骤

  1. 构造IOC容器
  2. 设置需要激活的环境
  3. 注入配置类
  4. 启动刷新容器
package com.suirui.springanno.autowiredDemo;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.suirui.springanno.autowiredDemo.config.MainConfigAutoWired;
import com.suirui.springanno.autowiredDemo.config.MainConfigAutoWired2;
import com.suirui.springanno.autowiredDemo.entity.Red;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.util.Map;

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

        String[] beanNamesForType = ac.getBeanNamesForType(DataSource.class);
        for (String s : beanNamesForType) {
            System.out.println(s);
        }
        Map beansOfType = ac.getBeansOfType(DataSource.class);
        for (Map.Entry entry : beansOfType.entrySet()) {
            System.out.println(entry.getKey());
            ComboPooledDataSource ds = (ComboPooledDataSource) entry.getValue();
            String user = ds.getUser();
            String password = ds.getPassword();
            String driverClass = ds.getDriverClass();
            System.out.println("user: " + user + ",pwd: "+ password + ". driverClass: " + driverClass);
            System.out.println("");
        }


    }
}

Spring注解开发——25、自动装配-@Profile根据环境注册bean_第2张图片

你可能感兴趣的:(Spring注解开发)