13-Spring自动装配-@Profile

@Profile

@Profile 可以根据当前环境动态的选择是否启用当前配置文件,常用场景用来区分测试和线上环境.

我们编写一个获取数据库实例的例子,看一下具体使用,先引入 Maven 依赖:

<dependencies>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>4.3.9.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>testscope>
    dependency>

    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.16.20version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>5.1.8.RELEASEversion>
    dependency>
    
    <dependency>
        <groupId>c3p0groupId>
        <artifactId>c3p0artifactId>
        <version>0.9.1.2version>
    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:

  1. 在运行时,指定一个参数: -Dspring.profiles.active=release
  2. 在配置文件中写入一行配置: spring.profiles.active=release
  3. 调用applicationContext.getEnvironment().setActiveProfiles(“release”); // 这里支持激活多个环境

咖啡小馆

QQ群: 823971061 点击按钮入群

你可能感兴趣的:(Spring源码系列)