随笔 - 1162  文章 - 0  评论 - 16  阅读 - 59万 

一、@Profile

Spring 为我们提供的可以根据当前环境,动态的激活和切换一系列 组件的 功能。

例如:开发环境、测试环境、生产环境

不同的环境连接到不同的数据源:(/A)(/B)(/C)

以测试数据源为例:

(1)编写配置文件 db.properties

db.user=root
db.password=root
db.driverClass=com.mysql.jdbc.Driver

(2)加入数据库依赖:

        <!-- 数据库依赖 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>

(3)配置类:

@PropertySource(value = {"classpath:/db.properties"})  //读取外部配置文件
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware {

    @Value("${db.user}")   //使用@Value注解读取配置文件的值
    private String user;

    private StringValueResolver valueResolver;

    private String driverClass;


    @Profile("pre")
    @Bean
    public DataSource dataSourcePre(@Value("db.password") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mybatis_plus");
        return dataSource;
    }

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

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

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.valueResolver = resolver;
        //使用字符串解析器通过表达式来获取配置文件的值
        this.driverClass =  resolver.resolveStringValue("${db.driverClass}");
    }
}

测试:

    @Test
    public void test01() {
        AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);

        System.out.println("IOC容器创建完毕");

        String[] names = ioc.getBeanNamesForType(DataSource.class);

        for (String name : names) {
            System.out.println(name);
        }


        ioc.close();
    }

如果没有激活运行环境,默认会加载 默认环境"default"。

二、激活不同的运行环境

1、使用命令行动态参数

在虚拟机参数位置加装参数:

-Dspring.profiles.active=test 激活测试环境

IDEA:

Eclipse:

2、使用代码方式激活运行环境

    @Test
    public void test02() {
        //使用无参构造创建一个容器,创建一个 application 对象
        AnnotationConfigApplicationContext ioc = new  AnnotationConfigApplicationContext();

        //1.创建一个 application 对象
        //2.设置需要激活的环境
        ioc.getEnvironment().setActiveProfiles("test",  "dev");   //可写一个运行环境

        //3.注册主配置类
        ioc.register(MainConfigOfProfile.class);

        //4.启动刷新容器
        ioc.refresh();

        //根据类型获取组件
        String[] names =  ioc.getBeanNamesForType(DataSource.class);
        for (String name : names) {
            System.out.println(name);
        }

    }

总结:

(1)@Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件。

(2)还可以写在@Bean 上面,加了环境标识的 Bean,只有这个环境被激活的时候才能注册到容器中,默认是 default 环境;

(3)写在配置类上,只有指定的环境的时候,整个配置类里面的所有配置才能开始生效;

(4)没有标注环境标识的 bean,在任何环境下都是加载的;

posted on   格物致知_Tony  阅读(72)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
历史上的今天:
2020-11-14 Java 关键字:final
2020-11-14 Java 面向对象(十二)类的成员 之 代码块
2020-11-14 Java 关键字:static
点击右上角即可分享
微信分享提示

目录导航