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

你可能感兴趣的:(框架,Baeldung,学习笔记,spring,java,后端)