programing

Tymeleaf에서 스프링 애플리케이션 환경 구현

minimums 2023. 3. 14. 21:31
반응형

Tymeleaf에서 스프링 애플리케이션 환경 구현

My Spring Boot 어플리케이션은 다음 3가지 구성으로 실행됩니다.

  • application.properties --> 개발 환경용
  • application-test.properties --> 테스트 환경용
  • application-production.properties --> 실가동 환경용

애플리케이션이 실행 중인 Tymeleaf 환경에서 어떻게 접근할 수 있습니까?

Google Analytics 코드를 프로덕션 환경에만 포함해야 합니다.

한 번에 활성 프로필이 하나만 있는 경우 다음을 수행할 수 있습니다.

<div th:if="${@environment.getActiveProfiles()[0] == 'production'}">
  This is the production profile - do whatever you want in here
</div>

위의 코드는 Tymeleaf's Spring 사투리를 사용하여 콩에 접근할 수 있다는 사실에 기초하고 있습니다.@기호.그리고 물론Environment오브젝트는 항상 스프링빈으로 사용할 수 있습니다.

또, 주의해 주세요.Environment방법이 있다getActiveProfiles()문자열 배열을 반환합니다(그 때문에).[0]표준 스프링 EL을 사용하여 호출할 수 있습니다.

여러 프로파일이 동시에 활성화되어 있는 경우 보다 강력한 솔루션은 Tymeleaf의#arrays문자열이 존재하는지 확인하기 위한 유틸리티 객체production활성화 프로파일에 있습니다.이 경우 코드는 다음과 같습니다.

<div th:if="${#arrays.contains(@environment.getActiveProfiles(),'production')}">
     This is the production profile
</div>

뷰의 전역 변수를 설정할 수 있는 클래스를 추가합니다.

@ControllerAdvice
public class BuildPropertiesController {

    @Autowired
    private Environment env;

    @ModelAttribute("isProd")
    public boolean isProd() {
        return Arrays.asList(env.getActiveProfiles()).contains("production");
    }
}

그리고 나서${isProd}변수:

<div th:if="${isProd}">
     This is the production profile
</div>

또는 액티브한 프로파일명을 글로벌 변수로 설정할 수도 있습니다.

@ControllerAdvice
public class BuildPropertiesController {

    @Autowired
    private Environment env;

    @ModelAttribute("profile")
    public String activeProfile() {
        return env.getActiveProfiles()[0];
    }
}

그리고 나서${profile}변수(활성 프로파일이 1개 있는 경우):

<div>
     This is the <span th:text="${profile}"></span> profile
</div>

언급URL : https://stackoverflow.com/questions/23711541/get-spring-application-environment-in-thymeleaf

반응형