天天看点

SpringBoot获取application配置文件中参数的三种方式

application.yml中配置:

test:
   msg: hello springboot
           

方式一:使用@Value方式

@RestController  
 public class WebController {  
    @Value("${test.msg}")  
    private String msg;       

    @RequestMapping("/index1")   
    public String index1(){  

        return "方式一:"+msg;  

    } 

}
           

方式二:使用Environment方式

package Solin.controller;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.core.env.Environment;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class WebController {  
    @Autowired  
    private Environment env;  
      
    @RequestMapping("/index2")   
    public String index2(){  
        return "方式二:"+env.getProperty("test.msg");  
    }  
}
           

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

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

1、在application.yml中添加配置

application:
  serverConfig:
    address: localhost
    port: 22
    username: geiri
    password: 12345678
           

2、建配置类

package com.pn.ebs.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "application")
public class ApplicationProperties {

    private ServerConfig serverConfig = new ServerConfig();

    public ServerConfig getServerConfig() {
        return serverConfig;
    }
    public final class ServerConfig{
        private String address;
        private String port;
        private String username;
        private String password;
        // geter/setter 此处略
    }

}
           

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

3、使用

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

@Autowired
ApplicationProperties applicationProperties;
           

然后,具体使用:

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

这里是测试代码:

SpringBoot获取application配置文件中参数的三种方式
SpringBoot获取application配置文件中参数的三种方式
SpringBoot获取application配置文件中参数的三种方式

执行结果:

SpringBoot获取application配置文件中参数的三种方式