版權聲明:本文為博主原創文章,遵循 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