preface

As mentioned in the previous article, the @profile annotation is a difficult word to translate directly into English; Profile itself means “profile,” “profile,” and in other areas of programming, the term has come to mean a store of data for each user. In Spring Boot, the term is used to distinguish between different environments, such as development, test, and production.

The source code

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
    String[] value();
}
Copy the code

This annotation can pass multiple strings. @profile (“prod”) and @profile ({“test”,”master”}) are both valid

use

Typically used under @Configuration, annotate classes or methods that can return beans by filling in a string as a scenario or distinction.

@Configuration
@Profile("dev")
public class MyConfig {
    // your beans here
}
Copy the code

The above code registers the MyConfig class in Spring only when the Profile is dev.

Add “!” before the Profile name. That is, a Profile is not active before the corresponding Bean is registered.

.@Bean
@Profile("! test") // Test is not activated before the Bean is created
public MyBean myBean(a) {
    return newMyBean(); }...Copy the code

Activate the environment

The most recommended approach is to configure the environment variable on the computer: export SPRING_PROFILES_ACTIVE= PROd so that the registered environment is tied to the computer.

You can also set the startup parameter -dspring.profiles. Active =test to enable multiple environments at the same time, for example, -dspring.profiles. Active =test,master

You can also configure it in application.yml, or use the @ActiveProfiles annotation, but these are written directly in the source code and lose flexibility, so I won’t expand on them here.

Prod, dev, test, and so on are common abbreviations that are self-defined rather than spring-provided