目录
背景介绍
具体使用
一、新建配置文件
1、位置和路径
2、编写配置文件.properties
二、代码中引入并使用
1.类必须交由spring管理
2、使用注解@PropertySource指定配置文件
3、使用@Value引入值
大功告成!
背景介绍
spring项目,非springboot项目!
需求:一些远程调用的接口地址经常变动的值,想要放到配置文件中,在.java代码中使用注解引用(由spring自动注入进来)。
优点:这样变动的内容只需要改配置文件,不用改代码啦!
提示:方式有很多种,本文介绍一种,仅供参考。
具体使用
一、新建配置文件
1、位置和路径
建在src/main/resource路径下demo.properties ,未来路径就写classpath:demo.properties
建在src/main/resource路径下建个包demo包下demo.properties ,未来路径就写classpath:demo/demo.properties
2、编写配置文件.properties
#key=vlaue这种格式
demo_url=http://xxx/xxx/demo
demo_key=xxxxxxxxxxxxxxxxx
二、代码中引入并使用
1.类必须交由spring管理
1.类必须交由spring管理
换句话说,使用配置文件里值的那个类上要有个注解,可以是@Service、@Component..
2、使用注解@PropertySource指定配置文件
@PropertySource({"classpath:demo.properties"})
3、使用@Value引入值
@Value("${demo_url}")
@Service
@PropertySource({"classpath:demo.properties"})
public class DemoUtil {
@Value("${demo_url}")
private String DEMO_URL;
@Value("${demo_key}")
private String demoKey;
public String sendPost() throws IOException {
HttpPost httpPost = new HttpPost(DEMO_URL);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("charset", "UTF-8");
//...
}
}



