在项目中,很多时候需要用到一些配置的信息,这些信息可能在测试环境和生产环境下会有
不同的配置,后面根据实际业务情况有可能还会做修改,针对这种情况,我们不能将这些配置在代码中写死,最好就是写到配置文件中。比如可以把这些信息写到 application.yml 文件中。
少量属性配置
例如从文件读物orderUrl的值
# 配置微服务的地址
url:
# 订单微服务的地址
orderUrl: http://localhost:8002
方法:使用@Value("${key}")注解,可以为配置文件的key.
package com.example.controller;
import com.example.conf.DubboConfig;
import com.example.conf.MoreKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);
// 从application.yml文件中服务单个值
@Value("${url.orderUrl}")
private String url;
@GetMapping("/hello")
public String hello() {
LOGGER.info("yml文件中获取单个key值: "+ url);
return "success";
}
}
多个属性配置
有多个属性配置,可以将其封装成pojo
# 配置多个微服务的地址
url:
# 订单微服务的地址
orderUrl: http://localhost:8002
# 用户微服务的地址
userUrl: http://localhost:8003
# 购物车微服务的地址
shoppingUrl: http://localhost:8004
使用@ConfigurationProperties(prefix = “url”) 注解,prefix是yml文件中的前缀,yml文件的key会自动映射pojo中对应名称的属性。
@Component
@ConfigurationProperties(prefix = "url")
public class MicroServiceUrl {
private String orderUrl;
private String userUrl;
private String shoppingUrl;
// 省去get和set方法
}
另外一种方法:可以直接从配置文件读取信息,封装成pojo。
使用@PropertySource(“classpath:dubbo.properties”)注解,value是配置文件路径,和ConfigurationProperties不同的是,此方法的属性需要使用@Value()注解标注配置文件中对应的key。
package com.example.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 读取额外的配置文件的配置信息
*/
@Component
@PropertySource("classpath:dubbo.properties")
public class DubboConfig {
@Value("${dubbo.resAddress}")
private String resAddress;
@Value("${dubbo.appName}")
private String appName;
@Value("${dubbo.resUsername}")
private String resUsername;
@Value("${dubbo.resPassowrd}")
private String resPassowrd;
@Value("${dubbo.protocol}")
private String protocol;
@Value("${dubbo.port}")
private int port;
@Value("${dubbo.accepts}")
private int accepts;
@Value("${dubbo.connections}")
private int connections;
//set,get方法和toString()方法
}