How to Set Profiles for Spring

Activate and set the profiles so that the respective beans are registered in the container.

1. Programmatically via WebApplicationInitializer Interface

# In web applications
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
 
        servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}

2. Programmatically via ConfigurableEnvironment

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("dev");

3. Context Parameter in web.xml

# in the web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
</context-param>

4. JVM System Parameter

 -Dspring.profiles.active=dev

5. Environment Variable

# In a Unix environment, profiles can also be activated via the environment variable
export spring_profiles_active=dev

6. Maven Profile

# In every Maven profile, we can set a spring.profiles.active property
<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

# Its value will be used to replace the @spring.profiles.active@ placeholder in application.properties:
spring.profiles.active=@spring.profiles.active@

# enable resource filtering in pom.xml
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    ...
</build>

# append a -P parameter to switch which Maven profile will be applied
mvn clean package -Pprod

7. @ActiveProfile in Tests

@ActiveProfiles("dev")

Activating profiles priority rom highest to lowest priority
1、Context parameter in web.xml
2、WebApplicationInitializer
3、JVM System parameter
4、Environment variable
5、Maven profile

参考:Spring Profiles

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值