spring boot uses @ ConfigurationProperties




Sometimes, we want to read and automatically encapsulate the configuration file information into entity classes. In this way, we can use @ ConfigurationProperties in the code easily and conveniently. At this time, we can use @ ConfigurationProperties to automatically encapsulate the configuration information of the same kind into entity classes

First of all, in the configuration file, the information is as follows

connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1
  • 1
  • 2
  • 3

At this time, we can define an entity class to load profile information

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    private String username;
    private String remoteAddress;
    private String password ;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getRemoteAddress() {
        return remoteAddress;
    }
    public void setRemoteAddress(String remoteAddress) {
        this.remoteAddress = remoteAddress;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

We can also define @ ConfigurationProperties directly on the annotation of @ bean. This is a bean entity class, so we don't need @ Component and @ ConfigurationProperties

@SpringBootApplication
public class DemoApplication{

    //...

    @Bean
    @ConfigurationProperties(prefix = "connection")
    public ConnectionSettings connectionSettings(){
        return new ConnectionSettings();

    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

And then when we need to use it, we just inject it like this

@RestController
@RequestMapping("/task")
public class TaskController {

@Autowired ConnectionSettings conn;

@RequestMapping(value = {"/",""})
public String hellTask(){
    String userName = conn.getUsername();     
    return "hello task !!";
}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

If @ configurationproperties does not work, it may be the directory structure of the project. You can use @ EnableConfigurationProperties(ConnectionSettings.class) to specify which entity class to use to load the configuration information.




Added by jinky32 on Fri, 27 Mar 2020 17:40:32 +0200