栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring web项目使用注解方式使用配置文件?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring web项目使用注解方式使用配置文件?

目录

背景介绍

具体使用

一、新建配置文件

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管理

        换句话说,使用配置文件里值的那个类上要有个注解,可以是@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");
		
		//...
	}
}

大功告成!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/678936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号