This is the fifth day of my participation in Gwen Challenge

preface

The popularity of the SpringBoot framework has brought us a lot of convenience. Some global configuration problems used in the system are also used to put in the configuration file. On the one hand, when the latter is packaged and deployed online, if it is only a configuration problem, we do not need to pack extra, just modify the configuration file. On the other hand, global configuration of common attributes does not have to be declared every time in a project. This article mainly explains how to use objects to obtain properties in configuration files

The development process

1. The properties configuration file declares the following properties:

2. Entity class object declaration: Inject the object into the Spring container through the @Component and @ConfigurationProperties annotations. Later, inject the object into the container through the @AutoWired annotation, and get the corresponding property information through the GET method

@component@configurationProperties (prefix = "spring.redis") // Public class RedisConfig {private String host; private String password; private String timeout; private String port; public String getRedisHost() { return redisHost; } public void setRedisHost(String redisHost) { this.redisHost = redisHost; } public String getRedisPasswd() { return redisPasswd; } public void setRedisPasswd(String redisPasswd) { this.redisPasswd = redisPasswd; } public int getRedisTimeOut() { return redisTimeOut; } public void setRedisTimeOut(int redisTimeOut) { this.redisTimeOut = redisTimeOut; } public int getRedisPort() { return redisPort; } public void setRedisPort(int redisPort) { this.redisPort = redisPort; }}Copy the code

3. Quotes in the project:

As shown above, once the RedisConfig object is introduced, you can use the GET method to get property information for assignment. Of course, sometimes there may be a little configuration information, such as simple configuration of file upload or download path, if it is a little troublesome to use this method, you can directly reference the @value tag of Spring. Specific use is as follows:

. 1. Application. Yml in writing the upload file. Save the path = / home/server/file/upload / 2. The controller in writing public class UserController { @Value("${upload.file.save.path}") private String uploadFileSavePath; }Copy the code

If you have a better way or method, welcome to comment in the comment area, on the road of coding together