先说坑:配置完了之后不生效。
原因:直接new出来的对象,必须使用@autowire或者@resource出来才能自动装配上
过程:
1.先配项目中的yaml或者nacos中的yaml:(另起一行顶格)
nc:
client_id: 123
client_secret: 123
pubKey: 123
secret_level: 123
baseUrl: http://127.0.0.0:9080
username: 123
pwd: 123
busi_center: 123
grant_type: 123
usercode: 123
repeat_check: 123
busi_id: 123
2.这里注意三个注解缺一不可
@Data
@Component
@ConfigurationProperties(prefix="nc")
public class NCConfigVo {
public String client_id;
public String client_secret;
public String pubKey;
public String secret_level;
public String baseUrl;
public String username;
public String pwd;
public String busi_center;
public String grant_type;
public String usercode;
public String repeat_check;
public String busi_id;
}
3.测试 注意必须使用自动装配方式,new对象出来一辈子也是空的。!!!!!
@Resource
NCConfigVo ncConfigVo;
@RequestMapping("test")
public void test(){
System.out.println(JSON.toJSONString(ncConfigVo));
}
4.扩展下:如果自定义yaml咋办
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.List;
public class PropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
return sources.get(0);
}
}
@Component
@PropertySource(value="test.yml",factory=PropertySourceFactory.class)
public class TestBean{
@Value("${name}")
private String name;
}
一般不建议使用第五步骤,除非你想搞屎山程序