@Profile使用及SpringBoot获取profile值

2023-11-02

之前开发用过 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 "";
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@Profile使用及SpringBoot获取profile值 的相关文章

随机推荐