这篇文章主要围绕spring获取配置文件的值和spring获取配置文件的值展开,旨在为您提供一份详细的参考资料。我们将全面介绍spring获取配置文件的值的优缺点,解答spring获取配置文件的值的相
这篇文章主要围绕spring 获取配置文件的值和spring获取配置文件的值展开,旨在为您提供一份详细的参考资料。我们将全面介绍spring 获取配置文件的值的优缺点,解答spring获取配置文件的值的相关问题,同时也会为您带来Java中spring读取配置文件的几种方法示例、Java获取配置文件的值过程解析、spring @Value 获取配置文件为 null 常见的几种方式、spring boot 读取配置文件的方式的实用方法。
本文目录一览:- spring 获取配置文件的值(spring获取配置文件的值)
- Java中spring读取配置文件的几种方法示例
- Java获取配置文件的值过程解析
- spring @Value 获取配置文件为 null 常见的几种方式
- spring boot 读取配置文件的方式
spring 获取配置文件的值(spring获取配置文件的值)
Spring 获取配置文件的值


package com.hafiz.www.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* Desc:properties文件获取工具类
* Created by hafiz.zhang on 2016/9/15.
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
<!--第一种,通过类加载器进行获取properties文件流-->
in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
<!--第二种,通过类进行获取properties文件流-->
//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
props.load(in);
} catch (FileNotFoundException e) {
logger.error("jdbc.properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("jdbc.properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}
Spring boot 获取配置文件的值
使用注解 @Value
@Controller
public class TestController {
@Value("${server.port:Hello World22}")
private String message = "Hello World";
@RequestMapping("/test")
public void test(){
System.out.println("message:"+message);
}
}
Java中spring读取配置文件的几种方法示例
本篇文章中主要介绍了Java中spring读取配置文件的几种方法示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
Spring读取配置XML文件分三步:
一.新建一个Java Bean:
package springdemo; public class HelloBean { private String helloWorld; public String getHelloWorld() { return helloWorld; } public void setHelloWorld(String helloWorld) { this.helloWorld = helloWorld; } }
二.构建一个配置文件bean_config.xml:
Hello!chb!
三.读取配置文件:
1.利用ClasspathXmlApplicationContext:
ApplicationContext context = new ClasspathXmlApplicationContext("bean_config.xml"); //这种用法不够灵活,不建议使用。 HelloBean helloBean = (HelloBean)context.getBean("helloBean"); System.out.println(helloBean.getHelloWorld());
ClasspathXmlApplicationContext实现了接口ApplicationContext,ApplicationContext实现了beanfactory。其通过jdom进行XML配置文件的读取,并构建实例化Bean,放入容器内。
public interface beanfactory { public Object getBean(String id); } //实现类ClasspathXmlApplicationContext import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; public class ClasspathXmlApplicationContext implements beanfactory { private Map beans = new HashMap(); //(IOC:Inverse of Control/DI:Dependency Injection) public ClasspathXmlApplicationContext() throws Exception { SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(this.getClass().getClassLoader().getResourceAsstream("beans.xml")); //构造文档对象 Element root=doc.getRootElement(); //获取根元素HD List list=root.getChildren("bean");//取名字为disk的所有元素 for(int i=0;i)element.getChildren("property")) { String name = propertyElement.getAttributeValue("name"); //userDAO String bean = propertyElement.getAttributeValue("bean"); //u Object beanObject = beans.get(bean);//UserDAOImpl instance String methodName = "set" + name.substring(0, 1).toupperCase() + name.substring(1); System.out.println("method name = " + methodName); Method m = o.getClass().getmethod(methodName, beanObject.getClass().getInterfaces()[0]); m.invoke(o, beanObject); } } } public Object getBean(String id) { return beans.get(id); } }
beanfactory是一个很根的接口,ApplicationContext和ClasspathXmlApplicationContext都实现了接口beanfactory,所以也可以这么写:
ApplicationContext context = new ClasspathXmlApplicationContext("bean_config.xml"); HelloBean helloBean = (HelloBean)context.getBean("helloBean"); beanfactory factory= new ClasspathXmlApplicationContext("bean_config.xml"); HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
ClasspathXmlApplicationContext层级关系如下:
2.利用FileSystemResource读取
Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/bean_config.xml"); beanfactory factory = new Xmlbeanfactory(rs); HelloBean helloBean = (HelloBean)factory.getBean("helloBean"); System.out.println(helloBean.getHelloWorld());
注意:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常。
Spring读取properties配置文件
介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取:
一.利用spring读取properties 文件
还利用上面的HelloBean.java文件,构造如下bean_config.properties文件:
helloBean.class=springdemo.HelloBean helloBean.helloWorld=Hello!HelloWorld!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.PropertiesBeanDeFinitionReader来读取属性文件。
BeanDeFinitionRegistry reg = new DefaultListablebeanfactory(); PropertiesBeanDeFinitionReader reader = new PropertiesBeanDeFinitionReader(reg); reader.loadBeanDeFinitions(new ClassPathResource("bean_config.properties")); beanfactory factory = (beanfactory)reg; HelloBean helloBean = (HelloBean)factory.getBean("helloBean"); System.out.println(helloBean.getHelloWorld());
二.利用java.util.Properties读取属性文件
比如,我们构造一个ip_config.properties来保存服务器ip地址和端口,如:
ip=192.168.0.1
port=8080
我们可以用如下程序来获得服务器配置信息:
InputStream inputStream = this.getClass().getClassLoader().getResourceAsstream("ip_config.properties"); Properties p = new Properties(); try { p.load(inputStream); } catch (IOException e1) { e1.printstacktrace(); } System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));
三.用接口类WebApplicationContext来取。
private WebApplicationContext wac; wac =WebApplicationContextUtils.getrequiredWebApplicationContext(this.getServletContext()); wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
其中,jdbcTemplate为spring配置文件中的一个bean的id值。
这种用法比较灵活,spring配置文件在web中配置启动后,该类会自动去找对应的bean,而不用再去指定配置文件的具体位置。
Java获取配置文件的值过程解析
这篇文章主要介绍了java获取配置文件的值过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
这篇文章主要介绍了java获取配置文件的值过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
java大型项目中都会很多系统常量,比如说数据库的账号和密码,以及各种token值等,都需要统一的管理,如果零落的散布到各个类等具体的代码中的话,在后期管理上将是一场灾难,所有需要对这些变量进行统一的管理,一般都会放到web-service.properties文件中,该文件在项目中的位置如下:
web-service.properties文件里的内容大概如下:
那么如何获取web-service.properties文件里的值呢?
1,需要在配置文件里配置Spring的PropertyPlaceholderConfigurer,具体格式如下:
classpath:conf/web-service.properties
2,编写通用类
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PropUtils { private static Logger logger = LoggerFactory.getLogger(PropUtils.class); private static Properties properties; static { InputStream in = null; try { properties = new Properties(); in = PropUtils.class.getResourceAsstream("/conf/web-service.properties"); properties.load(in); } catch (IOException e) { e.printstacktrace(); } } public static String getProp(String key){ return properties.getProperty(key); } }
3,调用通用类
String maxWait = PropUtils.getProp("maxWait_2");
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小编。
spring @Value 获取配置文件为 null 常见的几种方式
第一种方式:
xx.properties 属性名称错误,未与@Value("${xxx}") 进行对应
第二种方式:
该类未注入到spring bean容器中
@Component
@Controller
@Service
# 上面未注入,使用 @Autowired 会报错
@Autowired
第三种方式:
采用 new 等方式获取该对象
@Component
class TestValue{
@Value("${tag}")
private String tagValue;
}
class Test{
...
TestValue testValue = new TestValue()
}
\
第四种方式
将该属性 用 static final 等字眼进行 修饰
@Value("${value}")
private static String value; //错误
@Value("${value}")
private final String value; //错误
第五种方式
该属性名 大写
@Value("${value}")
private static String VALUE; //错误
参考文档:https://blog.csdn.net/zzmlake/article/details/54946346
第五种方式 是我真正遇到的,若还有其他方式会导致@Value("${xxx}") 为null ,
请在下方留言,
spring boot 读取配置文件的方式
spring boot 进一步封装了spring原来的配置,让程序猿们轻松了很多,真的很感谢spring boot
在日常代码中,会经常遇到读取配置文件属性到自己写的业务逻辑中,spring boot提供了两种方式(我的知道的)
1)@Value
@Value("${配置文件属性名称}")
例如
@Value("${agr-farmer.url}")//将agr-farmer.url 属性值放入Url中。
private String Url;
配置文件
agr-farmer.url= 127.0.0.1:8009/app
如果多个属性该怎么办?
利用注解 @ConfigurationProperties
@Component
@ConfigurationProperties(prefix="agr-farmer-config")
public class AgrFarmer {
// virtuals 下的键值对
private Map<String, String> virtuals = new HashMap<>();
//普通值
private String key;
//省略get,set方法
}
配置文件 格式是yml
agr-farmer-config:
virtuals:
key1: value1#key:value
key2: value2#key:value
key: T1KMKnylX #单值
关于spring 获取配置文件的值和spring获取配置文件的值的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Java中spring读取配置文件的几种方法示例、Java获取配置文件的值过程解析、spring @Value 获取配置文件为 null 常见的几种方式、spring boot 读取配置文件的方式等相关内容,可以在本站寻找。
本文标签: