@Profile使用及SpringBoot获取profile值

之前开发用过 maven 的环境隔离,现在使用springboot的@Profile功能,发现spring体系真的大到我只是学习了皮毛。相比面试问的 IOC,bean的作用域等,突然觉得很可笑。

官方文档关于 Profile 的使用
https://docs.spring.io/spring-boot/docs/2.0.5.RELEASE/reference/htmlsingle/#boot-features-profiles

  1. @Profile注解使用范围:
    @Configration 和 @Component 注解的类及其方法,其中包括继承了@Component的注解:@Service、@Controller、@Repository等…

  2. @Profile可接受一个或者多个参数,例如:

@Service
@Profile({"prod","default"})

Demo

参考: https://blog.csdn.net/zknxx/article/details/77906096

先看项目架构体系,只需要看展示的类,其他不用管

在这里插入图片描述

application.properties 配置文件
spring.profiles.active=prod,default
service
public interface ProfileService {
    String getMsg();
}
service.impl
@Service
@Profile("dev")
public class DevServiceImpl implements ProfileService {

    public DevServiceImpl() {
        System.out.println("我是开发环境。。。。。");
    }

    @Override
    public String getMsg() {
        StringBuilder sb = new StringBuilder();
        sb.append("我在开发环境,").append("我只能吃加班餐:大米饭。。。。");
        return sb.toString();
    }
}

@Service
@Profile({"prod","default"})
public class ProdServiceImpl implements ProfileService {

    public ProdServiceImpl() {
        System.out.println("我是生产环境。。。。。");
    }

    @Override
    public String getMsg() {
        StringBuilder sb = new StringBuilder();
        sb.append("我在生产环境,").append("我可以吃鸡鸭鱼牛羊肉。。。。");
        return sb.toString();
    }

}

controller
@Profile("dev")
@RestController
public class DevController {

    @Autowired
    private ProfileService profileService;

    @RequestMapping(value = "/")
    public String dev(){
        return "hello-dev\n"+profileService.getMsg();
    }

}

@Profile("prod")
@RestController
public class ProdController {

    @Autowired
    private ProfileService profileService;

    @RequestMapping(value = "/")
    public String prod(){
        return "hello-prod\n"+profileService.getMsg();
    }

}


在application.properties 配置文件使用不同的环境会执行不同的方法。

那么问题来了,这个功能使如何实现的?如果让你设计你会怎么做?面试新题,啊哈哈哈哈

获取profile值

参考来源:一下找不到了…囧

使用profile帮我解决了不同环境使用不同配置的问题,那么如果我们需要在代码中获取这个profile的值怎么处理呢?

@Component
public class ProfileUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }

    // 获取当前环境参数  exp: dev,prod,test
    public static String getActiveProfile() {
        String []profiles = context.getEnvironment().getActiveProfiles();
        if( ! ArrayUtils.isEmpty(profiles)){
            return profiles[0];
        }
        return "";
    }
}
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值