Spring Boot系列之配置读取 | Spring For All

290 阅读2分钟
原文链接: www.spring4all.com

boot里面所有的配置信息都放在application.properties中,如果我们想读取配置中的值要怎么做呢?

还需要自己写个读取属性文件的工具类吗?完全不要,我们可以通过各种方式来读取里面的值。

当然写工具类也是一种方式,只是太麻烦了,既然boot中有封装好的实现,为什么不用呢。。

Environment方式读取

框架中有一个org.springframework.core.env.Environment类,可以读取application.properties中配置的值。

用法如下,我们可以看到直接将Environment注入进来,然后就可以使用getProperty方法来获取配置的值了,
参数是配置的名称。

@RestController
public class ConfigController {
    @Autowired
    private Environment env;

    /**
     * 通过配置的key获取value<br>
     * {key:.+}是为了解决通过url参数访问的时候小数点丢失的问题
     * @param key
     * @return
     */
    @RequestMapping("/config/{key:.+}")
    Object getConfig(@PathVariable String key) {
        return env.getProperty(key);
    }
}

我们获取下之前配置的tomcat端口,http://localhost/spring-boot/config/server.port可以看到输出的结果正是你配置的值。

@Value注解方式读取

用法如下,通过注解的方式将要读取的值映射到这个字段上面,然后就可以直接使用了。

@RestController
public class ConfigController {
    /**
     * 读取application.properties中的配置值
     */
    @Value("${server.context-path}")
    private String contextPath;

    @RequestMapping("/config/contextpath")
    Object getConfigContextPath() {
        return contextPath;
    }
}

获取contextPath http://localhost/spring-boot/config/contextpath

自定义配置文件读取方式

系统自带的application.properties是配置一些框架相关的参数,当我们有一些关于业务方面的配置,如果配置在application.properties中就有点不合适了,这个时候就需要自定义配置文件了。

在没用spring boot之前也是建个属性文件,然后里面配置好值,用工具类去读取

当然也可以用spring提供的PropertiesFactoryBean去读取

现在读取就更简单了

这边可以直接将配置信息映射成实体类,方便使用,首先定义个配置实体类

@ConfigurationProperties(locations = "classpath:config.properties", prefix = "config")
@Component
public class Config {
    @NotEmpty
    private String ip;
    private int port;
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }

}

加上@Component和@ConfigurationProperties注解

@ConfigurationProperties中的locations用来指定你配置文件所在的路径

@ConfigurationProperties中的prefix用来指定你配置名称的前缀,如config.ip, config就是你上面定义的前缀

这边在ip字段上还加了个@NotEmpty注解来防止忘记配置值了,如果你没配置ip的值,那么在启动的程序的时候框架将提示你

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.cxytiandi.config.Config@2af616d3 failed:

    Property: config.ip
    Value: null
    Reason: 不能为空


Action:

Update your application's configuration

然后我们创建个config.properties放在classpath下

config.ip=192.168.1.1
config.port=8080

使用就直接注入Config类就行了

@RestController
public class ConfigController {
    @Autowired
    private Config config;

    @RequestMapping("/config")
    Object queryConfig() {
        return config;
    }
}

这边通过地址获取下配置信息:http://localhost/spring-boot/config 可以看到结果

{"ip":"192.168.1.1","port":8080}

更多技术分享请关注微信公众号:猿天地

image.png