@Profile
@Profile 可以根据当前环境动态的选择是否启用当前配置文件,常用场景用来区分测试和线上环境.
我们编写一个获取数据库实例的例子,看一下具体使用,先引入 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!--测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--简化代码-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!--数据库连接-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
创建一个配置类:
package com.demon.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @author Demon-HY
* @date 2020-1-10
*/
@Configuration
public class ConfigOfProfile {
// 测试环境数据库配置
@Bean("releaseDataSource")
@Profile("release")
public DataSource releaseDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("test");
dataSource.setPassword("test");
return dataSource;
}
// 生产环境数据库配置
@Bean("prodDataSource")
@Profile("prod")
public DataSource prodDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://124.53.223.56:3306/test");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("prod");
dataSource.setPassword("prod");
return dataSource;
}
}
我们在配置类中定义了测试和生产两个环境的配置,接下来只需要设置对应的Profile就可以区分环境了,有两种方式可以指定Profile:
- 在运行时,指定一个参数: -Dspring.profiles.active=release
- 在配置文件中写入一行配置: spring.profiles.active=release
- 调用applicationContext.getEnvironment().setActiveProfiles(“release”); // 这里支持激活多个环境
咖啡小馆
QQ群: 823971061 点击按钮入群