Sometimes there is such a situation, we want to the configuration file information, read and automatically encapsulated into the entity class, this way, we use in the code is easier and more convenient,
At this point, we can use @configurationproperties, which can automatically encapsulate similar configuration information into entity classes.
First in the configuration file, this information is such a drop
Connection.username=Adminconnection.password=kyjufskifas2jsfsconnection.remoteaddress= 192.168. 1.1
There are two ways to use it:
1. Annotations on the class
To bind the data of the external configuration file properties to the attributes of the class
@Component @configurationproperties (prefix="Connection") Public classConnectionSettings {PrivateString username; PrivateString remoteaddress; PrivateString password; PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString getremoteaddress () {returnremoteaddress; } Public voidsetremoteaddress (String remoteaddress) { This. remoteaddress =remoteaddress; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; }}
2. Bind the return object of the Bean method and the external configuration file
@Bean " Connection " ) public connectionsettings connectionsettings () { returnNew connectionsettings (); } Public Static void Main (string[] args) { springapplication.run (demoapplication. class , args); }
Spring Boot uses @configurationproperties