Spring boot tool class static attribute injection and detailed explanation of multi environment configuration

Because you need to access mongodb, but the local development environment cannot directly connect to mongodb, you need to use 127.0.0 through SecureCRT 0.2 local IP proxy. However, after the program is deployed to the online production environment, you can directly access mongodb. Therefore, after developing the program, you always have to modify the IP of the mongodb server to submit the code, which is very inconvenient.

Instead of using the spring boot starter data mongodb provided with spring boot, Mongo Java driver is used to access mongodb. Therefore, some configurations for accessing mongodb need to be defined in the program, such as server address, IP port, database name... These configuration information is declared with a static variable of a tool class, and the value of the configuration information is saved in application In the YML configuration file. Injected through @ configurationproperties.

Static tool class definition

Properties are static:

Then inject through the non static set method:

Other classes obtain properties through public static get methods:

The value of prefix is in application Defined in YML

The complete code is as follows:

YML profile definition

Use profile to specify different configurations in different environments. Active specifies the active environment, such as dev or prod

test

Since mongodb custom configuration is used, use @ springbootapplication (exclude = mongoautoconfiguration. Class) to exclude mongodb configuration from spring boot.

Reference: spring boot static variable injection configuration file

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>