codememo

환경 변수나 시스템 속성이 아닌 속성 파일을 통해 액티브 스프링 3.1 환경 프로필을 설정하는 방법

tipmemo 2023. 9. 5. 20:30
반응형

환경 변수나 시스템 속성이 아닌 속성 파일을 통해 액티브 스프링 3.1 환경 프로필을 설정하는 방법

우리는 봄 3.1의 새로운 환경 프로파일 기능을 사용합니다.현재 애플리케이션을 배포하는 서버에서 환경 변수 spring.spring.active=xxxxxxxxx를 설정하여 활성 프로파일을 설정합니다.

배포하려는 war 파일에는 서버의 일부 환경 설정에 종속되지 않도록 스프링 앱 컨텍스트가 로드되는 환경을 설정하는 추가 속성 파일이 있어야 하므로 이 솔루션은 차선의 솔루션이라고 생각합니다.

어떻게 해야 할지 생각해봤는데,

ConfigurableEnvironment.setActiveProfiles()

프로그래밍 방식으로 프로파일을 설정할 수 있지만 언제 어디서 이 코드를 실행해야 할지는 아직 알 수 없습니다.봄의 배경이 되는 곳?메서드에 전달할 매개 변수를 속성 파일에서 로드할 수 있습니까?

업데이트: 활성 프로필을 설정하기 위해 구현할 수 있는 문서를 방금 찾았습니다.

web.xml

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>profileName</param-value>
</context-param>

사용.WebApplicationInitializer

이 접근 방식은 사용자가 사용하지 않을 때 사용됩니다.web.xml서블릿 3.0 환경에 있는 파일로 Java에서 Spring을 완전히 부트스트랩하고 있습니다.

class SpringInitializer extends WebApplicationInitializer {

    void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.getEnvironment().setActiveProfiles("profileName");
        rootContext.register(SpringConfiguration.class);
        container.addListener(new ContextLoaderListener(rootContext));
    }
}

어디에SpringConfiguration클래스에 주석이 달립니다.@Configuration.

Thomasz의 답변은 프로파일 이름이 web.xml에 정적으로 제공되거나 속성 파일에서 설정할 프로파일을 프로그래밍 방식으로 로드할 수 있는 새로운 XML 없는 구성 유형을 사용하는 경우에만 유효합니다.

여전히 XML 버전을 사용하고 있기 때문에 더 자세히 조사해 본 결과 다음과 같은 솔루션을 사용하여 자체적으로 구현할 수 있습니다.ApplicationContextInitializer여기서 속성 파일이 있는 새 속성 원본을 원본 목록에 추가하여 환경별 구성 설정을 검색할 수 있습니다.아래의 예에서 설정할 수 있습니다.spring.profiles.active의 재산.env.properties파일.

public class P13nApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static Logger LOG = LoggerFactory.getLogger(P13nApplicationContextInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        try {
            environment.getPropertySources().addFirst(new ResourcePropertySource("classpath:env.properties"));
            LOG.info("env.properties loaded");
        } catch (IOException e) {
            // it's ok if the file is not there. we will just log that info.
            LOG.info("didn't find env.properties in classpath so not loading it in the AppContextInitialized");
        }
    }

}

그런 다음 해당 이니셜라이저를 매개 변수로ContextLoaderListener당신에게 다음과 같은 봄의.web.xml:

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>somepackage.P13nApplicationContextInitializer</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

에도 적용할 수 있습니다.DispatcherServlet:

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>somepackage.P13nApplicationContextInitializer</param-value>
    </init-param>
</servlet>

어떤 이유에서인지 나에게는 오직 하나의 방법만이 가능합니다.

public class ActiveProfileConfiguration implements ServletContextListener {   
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.setProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "dev");
        System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
    }

....

 <listener>
     <listener-class>somepackahe.ActiveProfileConfiguration</listener-class>
 </listener>
 <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

다음은 P13nApplicationContextInitializer 접근 방식의 변형입니다.그러나 이번에는 JNDI로부터 env 속성에 대한 경로를 얻습니다.이 경우 JNDI 글로벌 환경 변수를 coacorrect/spring-profile = file:/tmp/env.properties로 설정합니다.

  1. Tomcat/tomee server.xml 파일입니다.<Environment name="coacorrect/spring-profile" type="java.lang.String" value="/opt/WebSphere/props"/>
  2. .xml을 tomcat/tomee에 합니다.<ResourceLink global="coacorrect/spring-profile" name="coacorrect/spring-profile" type="java.lang.String"/>
  3. 임의의 컨테이너에서 web.xml에 적절한 내용을 추가합니다.

    public class SpringProfileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{
    
    public static final Logger log = LoggerFactory.getLogger(SpringProfileApplicationContextInitializer.class);
    private static final String profileJNDIName="coacorrect/spring-profile";
    private static final String failsafeProfile="remote-coac-dbserver";
    
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
    
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
    
        try {
            InitialContext ic = new InitialContext();
            Object r1 = ic.lookup(profileJNDIName);
            if (r1 == null) {
                // try the tomcat variant of JNDI lookups in case we are on tomcat/tomee
                r1 = ic.lookup("java:comp/env/"+profileJNDIName);
            }
            if (r1 == null) {
                log.error("Unable to locate JNDI environment variable {}", profileJNDIName);
                return;
            }
    
            String profilePath=(String)r1;
            log.debug("Found JNDI env variable {} = {}",r1);
            environment.getPropertySources().addFirst(new ResourcePropertySource(profilePath.trim()));
            log.debug("Loaded COAC dbprofile path. Profiles defined {} ", Arrays.asList(environment.getDefaultProfiles()));
    
        } catch (IOException e) {
            // it's ok if the file is not there. we will just log that info.
            log.warn("Could not load spring-profile, defaulting to {} spring profile",failsafeProfile);
            environment.setDefaultProfiles(failsafeProfile);
        } catch (NamingException ne) {
            log.error("Could not locate JNDI variable {}, defaulting to {} spring profile.",profileJNDIName,failsafeProfile);
            environment.setDefaultProfiles(failsafeProfile);
        }
    }
    

    }

언급URL : https://stackoverflow.com/questions/8587489/how-to-set-active-spring-3-1-environment-profile-via-a-properites-file-and-not-v

반응형