今天来讲解一下在spring boot 里面如何动态的配置属性,我们一般会把属性放在resources目录下面,这个目录同时也是classpath,首先我们在这个目录下面创建一个placeholder.properties(当然也可以是.xml,.yml等格式的文件),然后我们在里面放一条key-value的值,就像下面这样
username=carlwang
然后这个资源文件就写好了,然后我们有两种方式可以在代码中取到这个username。
第一种,使用一个@Configuration的类,这个类主要是用来配置一些bean,他和我们传统的**.xml配置bean的方式的效果是一样的,只是写法或者表现形式不一样罢了,在这个类中配置一个 PropertyPlaceholderConfigurer 就可以了,代码如下
@Bean
public PropertyPlaceholderConfigurer createPropertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
Resource resource = new ClassPathResource("placeHolder.properties");
propertyPlaceholderConfigurer.setLocation(resource);
return propertyPlaceholderConfigurer;
}
这样就会在spring context下面创建一个PropertyPlaceholderConfigurer 的bean。
第二种方式,就是在要使用这个值的bean中加上一段注解,
@ConfigurationProperties(locations = "classpath:placeHolder.properties")
这个也可以将 placeHolder.properties加载进来,然后我们只需要在使用的那个类加上一个成员变量就可以了,例如
package com.example.controller;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* Created by wangrui on 16/5/16.
*/
@RestController
@Data
@ConfigurationProperties(locations = "classpath:placeHolder.properties")
public class IndexController {
public static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);
@RequestMapping(value = "/index")
public String home(@RequestParam("name") String param, @RequestParam("file") String commonsMultipartFile) {
String name = param;
return name;
}
@Value(value = "${username}")
private String username;
private String password;
private Map<String, String> database;
private String table;
}
以上就是我要介绍的两种加载资源文件的方式,总结一下,一种是采用代码的方式,编写一个生成一个bean的方法,另外一种是,在要是用的类上面加上一段注解,这两种方式都可行,大家在使用中,应该遵循自己项目的需求,选择合适的方式。