Usage of spring @ profile annotation
This article mainly introduces how to use @ profile in spring and under what circumstances.
First, let's talk about why we use this @ profile annotation@ The profile annotation is an annotation provided by spring to indicate the current running environment. The problem we often encounter in the process of normal development is that the development environment is a set of environment, QA testing is a set of environment, and online deployment is a set of environment. In this way, the configuration in the program will be modified many times from development to testing and then to deployment, especially from QA to online, so that QA can't guarantee whether it can run online after changing which configuration. In order to solve the above problems, we usually use a method, that is, configuration files, and then read different configuration files through different environments, so as to run our programs in different scenarios.
Then, the role of @ profile annotation in spring is reflected here. When spring uses Di for dependency injection, it can inject corresponding beans according to the current running environment. The most common is to use different datasource.
The following describes in detail how to realize the above functions through spring's @ profile annotation.
The first is the new Maven project
mvn archetype:generate -DarchetypeCatalog=internal
Here is the POM file:
Take a general look at the classes and interfaces in the project:
First, there is a speak method in the person class, which is provided under the pretext of movefactor. Chinese, English and German all implement this interface. However, the values in the @ profile of these three classes are different. By allocating different active profiles in spring test, you can call different speak methods.
Let's look at the code: movefactor interface
Person. java
Chinese. java
English. java
German. java
Testing with spring test
Operation results:
When you modify the value in @ activeprofile, the output changes.
If the main function is used for real development, testing and online, we need to set the following operation parameters:
-D followed by the spring attribute to be set can be used in the main function.
App. java
Operation results:
If you need to get the current active profile, you can get it through the instance of configurableapplicationcontext.
Finally, let's talk about how to set it in the background project of the web. At this time, we set it through XML:
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.