profile
使用說明:
@profile注解的作用是指定類或方法在特定的 Profile 環(huán)境生效钞楼,任何@Component或@Configuration注解的類都可以使用@Profile注解。
在使用DI來依賴注入的時候窘问,能夠根據(jù)@profile標明的環(huán)境枷踏,將注入符合當前運行環(huán)境的相應的bean屁置。
使用要求
@Component或@Configuration注解的類可以使用@profile
@Profile中需要指定一個字符串,約定生效的環(huán)境
@Profile的使用位置
@Prifile修飾類
DevProfile.java
@Configuration
@Profile("dev")
public class DevProfile {
private static final Logger log = LoggerFactory.getLogger(DevProfile.class);
@PostConstruct
public void init(){
log.info("-----this profile is dev-----");
}
}
TestProfile
@Configuration
@Profile("test")
public class TestProfile {
private static final Logger log = LoggerFactory.getLogger(TestProfile.class);
@PostConstruct
public void init(){
log.info("-----this profile is test-----");
}
}
通過指定profile的值啟動即可;
測試結(jié)果
dev
image
test
image
@Profile修飾方法
@Configuration
public class TestProfile {
private static final Logger log = LoggerFactory.getLogger(TestProfile.class);
@Profile("test")
@Bean
public ProfileDto getTest(){
return new ProfileDto("test");
}
@Profile("dev")
@Bean
public ProfileDto getDev(){
return new ProfileDto("dev");
}
}
PageController.java
@RequestMapping("/")
@RestController
public class PageController {
@Resource
private ProfileDto profileDto;
@GetMapping("/profileTest")
public ProfileDto profileTest(){
return profileDto;
}
}
測試結(jié)果
訪問:http://localhost:8082/profileTest
dev
{"env":"dev"}
test
{"env":"test"}
@Profile修飾注解
@Profile注解支持定義在其他注解之上材失,以創(chuàng)建自定義場景注解。這樣就創(chuàng)建了一個@Dev注解硫豆,
該注解可以標識bean使用于@Dev這個場景龙巨。后續(xù)就不再需要使用@Profile("dev")的方式,這樣即可以簡化代碼熊响。
注解 @DevEnv
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface DevEnv {
}
注解 @TestEnv
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface TestEnv {
}
@Configuration
public class TestProfile {
private static final Logger log = LoggerFactory.getLogger(TestProfile.class);
@TestEnv
@Bean
public ProfileDto getTest() {
return new ProfileDto("test");
}
@DevEnv
@Bean
public ProfileDto getDev() {
return new ProfileDto("dev");
}
}
測試方法跟結(jié)果跟修飾方法一致旨别,不在贅述。
激活 Profile
實際使用中汗茄,注解中標示了prod秸弛、test、dev等多個環(huán)境洪碳,
運行時使用哪個profile由spring.profiles.active控制递览,以下說明2種方式 :配置文件方式、命令行方式瞳腌。
配置文件方式
application.properties
spring.profiles.active=dev
application.yml
spring:
profiles:
active: dev
命令行方式
在打包后運行的時候绞铃,添加參數(shù).
java -jar deme-profile-SNAPSHOT.jar --spring.profiles.active=dev