Spring combat environment and profile

1. Configure the profile bean

Spring's solution for environment-specific beans is actually not much different from the build-time solution. Of course, in this process, it is necessary to decide which bean to create and which not to create according to the environment. However, Spring does not make such decisions at build time, but waits until runtime to determine. The result is that the same deployment unit (probably a WAR file) can be used in all environments without having to rebuild. In version 3.1, Spring introduced the function of bean profile. To use profiles, you first organize all the different bean definitions into one or more profiles, and make sure the corresponding profile is active when deploying the application to each environment. In Java configuration, you can use the @Profile annotation to specify which profile a bean belongs to . For example, in the configuration class, the DataSource of the embedded database might be configured as follows:

 

What I want you to notice is that the @Profile annotation is applied at the class level. It tells Spring that beans in this configuration class will only be created when the dev profile is activated. If the dev profile is not activated, methods annotated with @Bean will be ignored

Lose.

At the same time, you may also need to have a configuration suitable for production environment, as shown below

In this example, the corresponding bean will only be created when the prod profile is activated.

In Spring 3.1, the @Profile annotation can only be used at the class level. However, as of Spring 3.2, you can also use the @Profile annotation at the method level, along with the @Bean annotation. This way, you can place the declarations of the two beans in the same

In a configuration class, as shown below

There is a catch here, although each DataSource bean is declared in a profile and the corresponding bean will be created , there may be other beans that are not declared in a profile within the given profile . A bean without a profile specified is always created, regardless of which profile is activated .

 

1.2 Configuring profiles in XML

 

1.3 Activate profile

Spring relies on two separate properties : spring.profiles.active and spring.profiles.default. If the spring.profiles.active property is set, its value is used to determine which profile is active. But if the spring.profiles.active property is not set, then Spring will look for the value of spring.profiles.default. If neither spring.profiles.active nor spring.profiles.default is set, then there is no active profile, so only beans that are not defined .

 

There are various ways to set these two properties:
as initialization parameters of DispatcherServlet;
as context parameters of web applications;
as JNDI entries;
as environment variables;
as system properties of the JVM
;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325060889&siteId=291194637