首页 > 技术文章 > @Profile使用及SpringBoot获取profile值

xiang--liu 2019-08-29 17:07 原文

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Fmuma/article/details/82787500

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

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

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

    @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 "";
    }
}
 ————————————————
版权声明:本文为CSDN博主「淘气的二进制」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Fmuma/article/details/82787500

推荐阅读