@ConfigurationProperties
自定义一个配置类
在配置类中的属性(host,port,username,password,virtual_host会自动被赋值配置文件中以spring.amqp为前缀的属性值)。
注意自定义配置类中的属性名称必须配置文件中的后缀名称一样,如配置文件中有springboot.amqp,host=172.18.1.132,那么在类属性名称必须为host,否则host的赋值为null。
@Component
@ConfigurationProperties(prefix = "spring.amqp")
public class RabbitMQServiceImpl implements RabbitMQService {
private String host;
private int port;
private String username;
private String password;
private String virtual_host;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVirtual_host() {
return virtual_host;
}
public void setVirtual_host(String virtual_host) {
this.virtual_host = virtual_host;
}
}
配置文件中的设置
spring.amqp.host=172.18.8.88
spring.amqp.port=5672
spring.amqp.username=guest
spring.amqp.password=guest
spring.amqp.virtual_host=siid
@Value
@SpringBootApplication
@RestController
public class Applaction {
@Value("${com.zyd.type}")
private String type;
@Value("${com.zyd.title}")
private String title;
...
}
Environment
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private Environment env;
@Autowired
private ConfigBeanValue configBeanValue;
@RequestMapping("/env")
public Map<String, Object> env() throws UnsupportedEncodingException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", env.getProperty("com.zyd.type2"));
map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
return map;
}
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + configBeanValue.name +
" , age=" + configBeanValue.age +
"<p>get properties value by ''Environment'' :" +
//2、使用Environment读取
" , sex=" + env.getProperty("demo.sex") +
" , address=" + env.getProperty("demo.address");
}
}
当访问http://localhost:10003/gateway时,直接使用env.getProperty会出现乱码,则可以在application.properties中配置
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
然后修改IntelliJ IDEA,File --> Settings --> Editor --> File Encodings ,将最下方Default encoding for properties files设置为UTF-8,并勾选Transparent native-to-ascii conversion。