方案一:

  1. @Value("${spring.profiles.active}")
  2. private String profile;

方案二:

  1. @Component
  2. public class PrintSpringContext implements ApplicationContextAware {
  3. private static ApplicationContext applicationContext;
  4. @Override
  5. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  6. PrintSpringContext.applicationContext = applicationContext;
  7. }
  8. public static ApplicationContext getApplicationContext() {
  9. if (applicationContext == null) {
  10. throw new IllegalStateException("applicationContext not defined!");
  11. } else {
  12. return applicationContext;
  13. }
  14. }
  15. public String getRunModel() {
  16. String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
  17. if(profiles.length > 0){
  18. return profiles[0];
  19. }
  20. return null;
  21. }
  22. }

调用测试:

  1. @Component
  2. public class PrintConverService {
  3. @Value("${spring.profiles.active}")
  4. private String profile;
  5. @Autowired
  6. private PrintSpringContext printSpringContext;
  7. public String findPrintDomainUrl(){
  8. if(StringUtils.isEmpty(profile)){
  9. profile = printSpringContext.getRunModel();
  10. }
  11. if("develop".equalsIgnoreCase(profile)){
  12. return "";
  13. } else if("release".equalsIgnoreCase(profile)) {
  14. return "";
  15. }
  16. return null;
  17. }
  18. }