application.yml中配置:

  1. test:
  2. msg: hello springboot

方式一:使用@Value方式

  1. @RestController
  2. public class WebController {
  3. @Value("${test.msg}")
  4. private String msg;
  5. @RequestMapping("/index1")
  6. public String index1(){
  7. return "方式一:"+msg;
  8. }
  9. }

方式二:使用Environment方式

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.core.env.Environment;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class WebController {
  8. @Autowired
  9. private Environment env;
  10. @RequestMapping("/index2")
  11. public String index2(){
  12. return "方式二:"+env.getProperty("test.msg");
  13. }
  14. }

方式三: @ConfigurationProperties(prefix = “”) 注解

对于单个变量的配置,以上足以满足。但是当配置需要有很多的时候,通过【方式一】或【方式二】一个个写很麻烦。这里介绍使用 @ConfigurationProperties(prefix = “”) 注解形式,项目中使用 application.yml中参数配置

1、在application.yml中添加配置

  1. application:
  2. serverConfig:
  3. address: localhost
  4. port: 22
  5. username: geiri
  6. password: 12345678

2、建配置类

  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. @ConfigurationProperties(prefix = "application")
  5. public class ApplicationProperties {
  6. private ServerConfig serverConfig = new ServerConfig();
  7. public ServerConfig getServerConfig() {
  8. return serverConfig;
  9. }
  10. public final class ServerConfig{
  11. private String address;
  12. private String port;
  13. private String username;
  14. private String password;
  15. // geter/setter 此处略
  16. }
  17. }

说明一下:prefix = “application”是application.yml文件中 配置(如配置文件)的名称。ServerConfig 类,对应配置文件中的 serverConfig,还可以application下面扩展增加其他配置,只需在 ApplicationProperties增加 例如serverConfig 属性即可,类似于一个JavaBean。

3、使用
在使用的类中 @Autowired 一下ApplicationProperties。

  1. @Autowired
  2. ApplicationProperties applicationProperties;

然后,具体使用:

  1. ApplicationProperties.ServerConfig serverConfig = applicationProperties.getServerConfig();
  2. ShellUtil.shellCommand(serverConfig.getAddress(), serverConfig.getUsername(),serverConfig.getPassword(), descCommand);