Get spring application environment in thymeleaf

后端 未结 2 1466
暖寄归人
暖寄归人 2021-01-31 09:05

My Spring Boot application runs with 3 configurations:

  • application.properties --> for development environment
  • application-test.properties --> for test env
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 09:41

    Simply add this class which allows to set global variables for views:

    @ControllerAdvice
    public class BuildPropertiesController {
    
        @Autowired
        private Environment env;
    
        @ModelAttribute("isProd")
        public boolean isProd() {
            return Arrays.asList(env.getActiveProfiles()).contains("production");
        }
    }
    

    And then use ${isProd} variable in your thymeleaf file:

    This is the production profile

    Or you can set active profile name as a global variable:

    @ControllerAdvice
    public class BuildPropertiesController {
    
        @Autowired
        private Environment env;
    
        @ModelAttribute("profile")
        public String activeProfile() {
            return env.getActiveProfiles()[0];
        }
    }
    

    And then use ${profile} variable in your thymeleaf file (if you have one active profile):

    This is the profile

提交回复
热议问题