Maven 프로파일로 스프링 활성 프로파일을 설정하는 방법
빌드 도구로 maven을 사용하는 응용 프로그램이 있습니다.
다른 프로필에서 다른 속성을 설정하기 위해 maven 프로필을 사용하고 있습니다.
내가하고 싶은 것은 maven의 모든 활성 프로파일이 스프링 활성 프로파일로 이식되어 bean 서명 ( @profile) 에서 참조 할 수 있다는 것입니다 . 그러나 나는 그것을하는 방법을 잘 모르겠습니다.
예를 들어 : 다음 maven 설정을 고려하십시오.
<profiles>
<profile>
<id>profile1</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
</properties>
</profile>
<profile>
<id>profile2</id>
<properties>
</properties>
</profile>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
</properties>
</profile>
<profile>
<id>production</id>
<properties>
</properties>
</profile>
</profiles>
내가 가지고 봄을 원하는 다른 프로파일을 지정 밖으로 받는다는 실행 가정 profile1및 development활성 프로파일로.
예를 들어 봄에 활성화 할 프로필에 대한 정보를 보유하는 속성 파일과 같은 애플리케이션의 리소스를 필터링해야합니다.
예를 들어
spring.profile = ${mySpringProfile}
그리고 각 프로필에 대해이 변수 ( mySpringProfile) 의 값을 정의합니다 .
빌드 중에 현재 활성 프로필에 정의 된 값에 따라 필터링됩니다.
그런 다음 응용 프로그램의 부트 스트랩 중에이 파일에 따라 적절한 프로필을 선택합니다 (더 많은 정보를 제공하지 않았으므로 더 많은 도움을 줄 수는 없지만 매우 쉽습니다.
참고 : maven에서 현재 활성화 된 프로필 (-P 값을 보유하는 project.profiles.active와 같은 것)을 얻는 방법을 찾을 수 없으므로 각 프로필에 대해 새 변수를 설정해야합니다.
참고 2 : 웹 애플리케이션을 실행중인 경우이 중간 파일을 사용하는 대신 web.xml에서이 값을 필터링하십시오.
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${mySpringProfile}</param-value>
</context-param>
참고 3 : 이것은 실제로 나쁜 습관이며 런타임에 시스템 속성을 사용하여 프로필을 설정해야합니다.
2 개의 메이븐 + 스프링 프로파일을 동시에 전환하는 더 우아한 방법이 있습니다.
먼저 POM에 프로파일을 추가합니다 (주의-maven + spring 프로파일은 단일 시스템 변수에 의해 활성화 됨).
<profiles>
<profile>
<id>postgres</id>
<activation>
<activeByDefault>true</activeByDefault>
<property>
<name>spring.profiles.active</name>
<value>postgres</value>
</property>
</activation>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>h2</id>
<activation>
<property>
<name>spring.profiles.active</name>
<value>h2</value>
</property>
</activation>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
</dependency>
</dependencies>
</profile>
</profiles>
둘째 , spring에 대한 기본 프로필을 설정하십시오 (maven의 경우 이미 POM에 설정되어 있습니다). 웹 응용 프로그램의 경우 다음 줄을 삽입했습니다 web.xml.
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>postgres</param-value>
</context-param>
셋째 , 구성에 프로필 종속 빈을 추가합니다. 제 경우에는 (XML 구성) 다음과 같습니다.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mainDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties" ref="hibProps"/>
<property name="packagesToScan">
<list>
<value>my.test.model</value>
</list>
</property>
</bean>
...
<beans profile="postgres">
<bean name="mainDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/webchat" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
</bean>
</beans>
<beans profile="h2">
<bean name="mainDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:file:./newsdb;INIT=RUNSCRIPT FROM 'classpath:init.sql';TRACE_LEVEL_FILE=0" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
</beans>
이제 다음을 수행 할 수 있습니다.
mvn jetty:run또는mvn jetty:run -Dspring.profiles.active=postgres명령을 사용 하여 Postgres DB에서 내 웹 앱 실행- H2 DB에서 내 웹 앱 실행
mvn clean jetty:run -Dspring.profiles.active=h2
가장 먼저 필요한 것은 구성을 유지하기위한 두 개의 속성 파일입니다. 파일 이름은 application- {custom_suffix} .properties 패턴과 일치해야합니다. Maven 프로젝트의 src / main / resources 디렉터리에 기본 application.properties 파일 옆에 생성합니다.이 파일은 나중에 다른 하나를 활성화하고 두 프로필에서 공유하는 값을 유지하는 데 사용할 것입니다.
그런 다음 pom.xml을 수정할 시간입니다. 각 Maven 프로필에서 사용자 지정 속성을 정의하고 특정 프로필과 함께로드하려는 해당 속성 파일의 접미사와 일치하도록 해당 값을 설정해야합니다. 다음 샘플은 기본적으로 실행할 첫 번째 프로필도 표시하지만 필수는 아닙니다.
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>release</id>
<properties>
<activatedProperties>release</activatedProperties>
</properties>
</profile>
다음으로 동일한 파일의 빌드 섹션에서 Resources Plugin에 대한 필터링을 구성합니다. 그러면 이전 단계에서 정의한 속성을 리소스 디렉터리의 모든 파일에 삽입 할 수 있습니다. 이는 후속 단계입니다.
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
…
</build>
마지막으로 application.properties에 다음 줄을 추가합니다.
spring.profiles.active=@activatedProperties@
빌드가 실행되면 Resources Plugin은 활성 Maven 프로필에 정의 된 속성 값으로 자리 표시자를 대체합니다. 애플리케이션을 시작한 후 Spring 프레임 워크는 spring.profiles.active 속성 값으로 설명되는 활성 Spring 프로필의 이름을 기반으로 적절한 구성 파일을로드합니다. Spring Boot 1.3은 필터링 된 값에 대한 기본 Resources Plugin 구문을 대체하고 표기법 @activatedProperties@대신 사용 합니다 ${activatedProperties}.
완벽하게 작동했습니다. 이것이 당신을 도울 수 있기를 바랍니다.
저는 현재 Servlet 2.5 및 Java 6 만 지원하는 이전 서버 / 컨테이너에서 실행할 수 있어야하는 (내 통제 할 수없는 이유로) 작은 웹앱을 구축하고 있습니다. 또한 웹앱 구성이 완전해야한다는 요구 사항도 있습니다. 자체 포함되므로 시스템 변수 및 / 또는 JVM 매개 변수도 사용할 수 없습니다. 관리자는 배포를 위해 컨테이너에 놓을 수있는 각 환경에 대한 .war 파일을 원합니다.
내 webapp에서 Spring 4.x를 사용하고 있습니다. 이것이 활성 Maven 프로필이 활성 Spring 4.x 프로필을 설정하는 데 사용되도록 애플리케이션을 구성한 방법입니다.
pom.xml 파일 변경
내 POM 파일에 다음 비트를 추가했습니다. 내 POM은 모델 버전 4.0.0을 사용하고 있으며 빌드를 수행 할 때 Maven 3.1.x를 실행하고 있습니다.
<modelVersion>4.0.0</modelVersion>
...
<profiles>
<profile>
<id>dev</id>
<activation>
<!-- Default to dev so we avoid any accidents with prod! :) -->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>dev</spring.profiles.to.activate>
</properties>
</profile>
<profile>
<id>uat</id>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>uat</spring.profiles.to.activate>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<!-- This can be a single value, or a comma-separated list -->
<spring.profiles.to.activate>prod</spring.profiles.to.activate>
</properties>
</profile>
</profiles>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<webResources>
<webResource>
<filtering>true</filtering>
<directory>src/main/webapp</directory>
<includes>
<include>**/web.xml</include>
</includes>
</webResource>
</webResources>
<failOnMissingWebXml>true</failOnMissingWebXml>
</configuration>
</plugin>
...
</plugins>
</build>
web.xml 파일 변경
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Setup for root Spring context
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>
<!--
Jim Tough - 2016-11-30
Per Spring Framework guide: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-environment
...profiles may also be activated declaratively through the spring.profiles.active
property which may be specified through system environment variables, JVM system
properties, servlet context parameters in web.xml, or even as an entry in JNDI.
-->
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${spring.profiles.to.activate}</param-value>
</context-param>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
Now I can create Java-based configuration classes like the one below that will only be used when a particular Spring profile is active.
@Configuration
@Profile({"dev","default"})
@ComponentScan
@EnableTransactionManagement
@EnableSpringDataWebSupport
public class PersistenceContext {
// ...
}
For a Spring Boot application, one can add a property in the Maven profile in pom.xml and then reference that property in application.properties.
Add Maven profiles to pom.xml with, for example, a property called spring.profile.from.maven:
<profiles>
<profile>
<id>postgres</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profile.from.maven>postgres</spring.profile.from.maven>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>noDb</id>
<properties>
<spring.profile.from.maven>noDb</spring.profile.from.maven>
</properties>
</profile>
</profiles>
Reference the Maven property in application.properties:
spring.profiles.include=@spring.profile.from.maven@
With this setup, running maven with the postgres Maven profile or with no profile adds the postgres Spring profile to the list of Spring's active profiles, while running maven with the noDb Maven profile adds the noDb Spring profile to the list of Spring's active profiles.
Add placeholder ${activeProfile} in web.xml:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${activeProfile}</param-value>
</context-param>
Set properties in pom.xml for each profile:
<profiles>
<profile>
<id>profile1</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activeProfile>profile1</activeProfile>
</properties>
</profile>
<profile>
<id>profile2</id>
<properties>
<activeProfile>profile2</activeProfile>
</properties>
</profile>
</profiles>
Add maven-war-plugin and set <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors> to replace the placeholder when running mvn package -Pprofile1 or mvn package -Pprofile2:
<build>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
</configuration>
</plugin>
</build>
ReferenceURL : https://stackoverflow.com/questions/25420745/how-to-set-spring-active-profiles-with-maven-profiles
'programing' 카테고리의 다른 글
| "일시 중단"상태와 높은 DiskIO는 sp_who2에서 무엇을 의미합니까? (0) | 2021.01.15 |
|---|---|
| (JSON :: ParserError)“{N} : 'alihack <% eval request (\ "alihack.com \") %>에 예기치 않은 토큰이 있습니다. (0) | 2021.01.15 |
| Dagger 2.0을 사용하여 단위 테스트에서 모듈 / 종속성을 어떻게 재정의합니까? (0) | 2021.01.15 |
| iOS 9 시작 화면이 검은 색입니다. (0) | 2021.01.15 |
| for <> 구문은 일반 수명 제한과 어떻게 다릅니 까? (0) | 2021.01.15 |