美文网首页spring 相关
spring注解--Profile

spring注解--Profile

作者: aix91 | 来源:发表于2019-01-02 14:00 被阅读0次

1. 作用

根据当前环境,动态的激活切换注入的bean;使用该功能,可以实现测试环境,生产环境的切换。

2. 用法

  • @Profile(属性名):默认是“default”
  • 环境参数的设置
    1. 虚拟机参数里面设置:-Dspring.profiles.active=test
    2. 使用代码的方式:使用无参构造器,然后设置Environment
  • @Profile可以放在@Bean上,也可以放在类上

3. 实例

  1. 给要注入的bean设置profile属性
@Configuration
public class MainConfig {
    @Profile("test")
    @Bean(name = "test")
    public TestBean testBean() {
        return new TestBean();
    }
    @Profile("dev")
    @Bean(name = "dev")
    public DevBean devBean() {
        return new DevBean();
    }
    @Profile("prod")
    @Bean(name = "prod")
    public ProdBean prodBean() {
        return new ProdBean();
    }
}
  1. 设置context环境属性
public class ProfileDemo {
    public static void main(String[] args) {
//        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        //构建无参构造器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //设置环境变量
        context.getEnvironment().setActiveProfiles("test");
        //注册configuration 类
        context.register(MainConfig.class);
        context.refresh();
        Arrays.stream(context.getBeanDefinitionNames()).forEach(p ->
                System.out.println(p)
        );
    }
  1. 输出,查看注入到容器中的bean
mainConfig
...
test --> 注入的testBean

4. Notes

没有设置profile属性的bean,在任何环境下都可以注入。

相关文章

  • Spring注解@profile

    Spring中@profile与maven中的profile很相似,通过配置来改变参数。 例如在开发环境与生产环境...

  • spring注解--Profile

    1. 作用 根据当前环境,动态的激活切换注入的bean;使用该功能,可以实现测试环境,生产环境的切换。 2. 用法...

  • Spring @Profile 注解介绍

    在这之前先看一下@Conditional注解 以下是对官方描述的简单翻译@Conditional这个注解表示'只有...

  • Spring 注解版

    文末有彩蛋 @Scope bean的生命周期 @Value 自动装配 @Profile AOP Spring注解驱动开发

  • Spring @Profile注解进阶使用

    @Profile("a") : 在a环境下生效@Profile("!a") : 在除a之外的其他环境下生效@Pr...

  • logback-结合spring profile使用

    什么是spring profile? spring profile就是spring的多环境配置功能,可以通过执行激...

  • Spring - 实战指南

    Spring Spring - Profile Spring - 参数绑定 Spring Boot Spring ...

  • 【转载】Maven管理SpringBoot Profile

    Maven管理SpringBoot Profile 1. Spring Profile Spring可使用Prof...

  • SpringBoot之条件注解

    背景 之前写过关于Spring和Maven的profile的区别 maven profile VS spring ...

  • spring02

    Spring相关注解 Spring注解开发 集成Spring测试框架 重点:重点掌握Spring相关注解。@Con...

网友评论

    本文标题:spring注解--Profile

    本文链接:https://www.haomeiwen.com/subject/imkzlqtx.html