spring 注解学习 四 profile注解

四、@Profile的作用

4.1、Profile注解的定义

使用@profile注解的目的是为了多环境开发,比如开发环境使用dev, 生产环境使用prod,就可以使用@Profile注解实现不同的开发环境使用不同的数据源。

@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();

}

4.2、使用案例

Profile既可以标注在方法上,也可以标注在类上。本例只演示标注在方法上

@Configuration
@PropertySource("classpath:/dataSource.properties")
public class ProfileConfig implements EmbeddedValueResolverAware {

    @Value("${mysql.user}")
    private String user;
    @Value("${mysql.password}")
    private String password;
    private String url;
    private String driver;

    private  StringValueResolver stringValueResolver;


    @Profile("dev")
    @Bean("devDataSource")
    public DataSource dataSourceDev() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driver);
        return dataSource;
    }


    @Profile("test")
    @Bean("testDataSource")
    public DataSource dataSourceTest() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driver);
        return dataSource;
    }

    @Profile("prod")
    @Bean("proDataSource")
    public DataSource dataSourcePro() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driver);
        return dataSource;
    }

    //获取字符串的解析器
    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.stringValueResolver=resolver;
        driver=stringValueResolver.resolveStringValue("${mysql.driver}");
        url=stringValueResolver.resolveStringValue("${mysql.url}");
    }
}

4.3、激活方式

1、通过jvm参数

-Dspring.profiles.active=test

2、通过spring中的Environment环境变量

@Test
    public void fun02(){
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("dev");
        context.register(ProfileConfig.class);
        context.refresh();
        String[] beanNamesForType = context.getBeanNamesForType(DataSource.class);
        for (String name:beanNamesForType){
            System.out.println(name);
        }

    }

3、在springboot中还可以通过@ActiveProfiles注解来激活

@ActiveProfiles("dev")
posted @ 2021-03-16 22:31  阿瞒123  阅读(359)  评论(0编辑  收藏  举报