1. spring如何动态加载配置文件,就是配置文件修改了,application.xml如何能读取到
项目,需要访问多个数据库,而且需要在服务器运行不重新启动的情况下,动态的修改spring中配置的数据源datasource,在网上找了很多资料,最后找到了适合我的方法,下面总结一下。
spring的配置文件是在容器启动的时候就加载到内存中的,如果手动改了application.xml,我们必须要重新启动服务器配置文件才会生效。而在spring中提供了一个类WebApplicationContext,这个类可以让你获得一些bean,可以修改内存中的信息,我就是通过这个类来实现的。下面是我具体的代码。
package com.southdigital.hospital;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class ChangeSpringConfig extends HttpServlet
{
private String ipAddress = "127.0.0.1";
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//先取得servleContext对象,提供给spring的WebApplicationUtils来动态修改applicationContext.xml
ipAddress = request.getParameter("ipAddress");
System.out.println(ipAddress);
ServletContext servletContext = this.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
ComboPooledDataSource cpds = (ComboPooledDataSource) applicationContext.getBean("dataSource");
cpds.setJdbcUrl("jdbc:mysql://"+ipAddress+":3306/ssh");
}
}
注意:通过这种方法修改applicationContext.xml文件的时候用c3p0,而不可以用dbcp,dbcp不支持动态修改读取到内存里面的数据。
spring 3.1已经支持了。
2. Spring中读取bean配置文件的几种方式
BeanFactory允许InputStream作为构造函数的参数,也可以org.springframework.core.io.Resource接口。下面这个例子是用ClassPathResource作为参数:
Resource resource = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resource);
ActionBean action = (ActionBean) factory.getBean("actionBean");
如果同一个Bean在配置文件有多个bean的定义,则用下面的方法取得所有的对象:
Resource resource = new ClassPathResource("bean.xml");
ListableBeanFactory factory = new XmlBeanFactory(resource);
Map helloBeans = factory.getBeansOfType(ActionBean.class, false, false);
3. 如何在spring中读取properties配置文件里面的信息
一个系统中通常会存在如下一些以Properties形式存在的配置文件
1.数据库配置文件demo-db.properties:
2.消息服务配置文件demo-mq.properties:
3.远程调用的配置文件demo-remote.properties:
一、系统中需要加载多个Properties配置文件
应用场景:Properties配置文件不止一个,需要在系统启动时同时加载多个Properties文件。
配置方式:
<!-- 将多个配置文件读取到容器中,交给Spring管理 -->
我们也可以将配置中的List抽取出来:
<!-- 将多个配置文件位置放到列表中 -->
<!-- 将配置文件读取到容器中,交给Spring管理 -->
二、整合多工程下的多个分散的Properties
应用场景:工程组中有多个配置文件,但是这些配置文件在多个地方使用,所以需要分别加载。
注意:其中order属性代表其加载顺序,而为是否忽略不可解析的 Placeholder,如配置了多个PropertyPlaceholderConfigurer,则需设置为true。这里一定需要按照这种方式设置这两个参数。
三、Bean中直接注入Properties配置文件中的值
应用场景:Bean中需要直接注入Properties配置文件中的值 。例如下面的代码中需要获取上述demo-remote.properties中的值:
<!-- 这种加载方式可以在代码中通过@Value注解进行注入,
可以将配置整体赋给Properties类型的类变量,也可以取出其中的一项赋值给String类型的类变量 -->
<!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->
<!-- <util:properties/> 标签的实现类是PropertiesFactoryBean,
直接使用该类的bean配置,设置其locations属性可以达到一个和上面一样加载多个配置文件的目的 -->
Client类中使用Annotation如下:
四、Bean中存在Properties类型的类变量
应用场景:当Bean中存在Properties类型的类变量需要以注入的方式初始化
1. 配置方式:我们可以用(三)中的配置方式,只是代码中注解修改如下
2. 配置方式:也可以使用xml中声明Bean并且注入
<!-- 可以使用如下的方式声明Properties类型的FactoryBean来加载配置文件,这种方式就只能当做Properties属性注入,而不能获其中具体的值 -->
<!-- 远端调用客户端类 -->
上述的各个场景在项目群中特别有用,需要灵活的使用上述各种配置方式。
http://blog.sina.com.cn/s/blog_6940cab30101evjf.html
4. spring中怎么通过编码的方式指定需要加载的配置文件路径
如果spring的配置文件在src路径下,在web.xml中要加载配置文件,
路径应该是这样:classpath:spring(文件名字).xml
如果在其他路径下,就要写绝对路径了。
解决方法
public void getCsisUrl(){
Properties p = new Properties();
try{
FileInputStream in = new FileInputStream(ServletActionContext.getRequest().getRealPath("/WEB-INF/classes/demo.properties"));
p.load(in);
in.close();
String csisUrl= p.getProperty("csisUrl");
//System.out.println(csisUrl);
}catch(Exception e){
e.printStackTrace();
}
}
5. SpringBoot 如何优雅读取配置文件10分钟教你搞定
很多时候我们需要将一些常用的配置信息比如阿里云 oss 配置、发送短信的相关信息配置等等放到配置文件中。
下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
application.yml 内容如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: [email protected]:location: 湖北武汉加油中国加油books: -name: 天才基本法description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 -name: 时间的秩序description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 -name: 了不起的我description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?
1.通过 @value 读取比较简单的配置信息
使用 @Value("${property}") 读取比较简单的配置信息:
@Value("${wuhan2020}")String wuhan2020;
需要注意的是 @value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。
2.通过@ConfigurationProperties读取并与 bean 绑定
LibraryProperties 类上加了 @Component 注解,我们可以像使用普通 bean 一样将其注入到类中使用。
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@Component@ConfigurationProperties(prefix ="library")@Setter@Getter@{privateString location;privateList books;@Setter@Getter@ToStringstaticclassBook{ String name; String description; }}
这个时候你就可以像使用普通 bean 一样,将其注入到类中使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/** *@authorshuang.kou */@ntsInitializingBean{privatefinalLibraryProperties library;(LibraryProperties library){this.library = library; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}
控制台输出:
湖北武汉加油中国加油[LibraryProperties.Book(name=天才基本法, description........]
3.通过@ConfigurationProperties读取并校验
我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式:
my-profile:name: Guide哥email: koushuangbwcx@
ProfileProperties 类没有加 @Component 注解。我们在我们要使用ProfileProperties 的地方使用@
EnableConfigurationProperties注册我们的配置 bean:
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@{@NotEmptyprivateString name;@Email@NotEmptyprivateString email;//配置文件中没有读取到的话就用默认值privateBooleanhandsome =Boolean.TRUE;}
具体使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/** *@authorshuang.kou */@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class){privatefinalProfileProperties profileProperties;(ProfileProperties profileProperties){this.profileProperties = profileProperties; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(profileProperties.toString()); }}
因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:koushuangbwcx@Origin:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress
我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:
ProfileProperties(name=Guide哥, [email protected], handsome=true)
4.@PropertySource读取指定 properties 文件
importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@SetterclassWebSite{@Value("${url}")privateString url;}
使用:
@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn/
5.题外话:Spring 加载配置文件的优先级
Spring 读取配置文件也是有优先级的,直接上图:
原文链接:https://www.toutiao.com/a6791445278911103500/?log_from=7f5fb8f9b4b47_1640606437752
6. springmvc中如何从配置文件中读取信息
1、第一步,先新建一个.properties文件,
app.properties里面内容
admin=admin
test=test
2、第二步,新建一个xml文件,在applicationContext.xml,
<!-- 用来解析Java Properties属性文件值(注意class指定的类)-->
<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:app.properties</value>
</list>
</property>
</bean>
<!-- 把properties里面的信息读进来: -->
<bean id="report" class="java.lang.String">
<constructor-arg value="${admin}"/>
</bean>
7. java 怎么读取配置文件
一.读取xml配置文件
(一)新建一个java bean(HelloBean. java)
java代码
(二)构造一个配置文件(beanConfig.xml)
xml 代码
(三)读取xml文件
1.利用
java代码
2.利用FileSystemResource读取
java代码
二.读取properties配置文件
这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
我们还利用上面的HelloBean. java文件,构造如下beanConfig.properties文件:
properties 代码
helloBean.class=chb.demo.vo.HelloBean
helloBean.helloWorld=Hello!chb!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.来读取属性文件
java代码
(二)利用java.util.Properties读取属性文件
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
properties 代码
ip=192.168.0.1
port=8080
三.读取位于Jar包之外的properties配置文件
下面仅仅是列出读取文件的过程,剩下的解析成为properties的方法同上
1 FileInputStream reader = new FileInputStream("config.properties");
2 num = reader.read(byteStream);
3 ByteArrayInputStream inStream = new ByteArrayInputStream(byteStream, 0, num);
四.要读取的配置文件和类文件一起打包到一个Jar中
String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码
JarFile currentJar = new JarFile(currentJarPath);
JarEntry dbEntry = currentJar.getJarEntry("包名/配置文件");
InputStream in = currentJar.getInputStream(dbEntry);
//以上YourClassName是class全名,也就是包括包名
修改:
JarOutputStream out = new FileOutputStream(currentJarPath);
out.putNextEntry(dbEntry);
out.write(byte[] b, int off, int len); //写配置文件
。。。
out.close();
8. 请教,如何spring boot里动态读取配置文件
这个跟spring mvc一样的啊,首先你看你的spring-mvc.xml 有没有配置defaultViewResolver,
<property name="prefix" value="/webpage/" />
<property name="suffix" value=".jsp" />
然后你在action的方法中如果1.标注了@ResponseBody,返回字符串的话是通过write输出到页面。2.没有标注这个,spring mvc会到配置的目录下 找相应的jsp。比如返回 "hello",它就在 webpage/目录下找hello.jsp。 返回 "user/login",它就会找 webpage/user/login.jsp
9. Java中spring读取配置文件的几种方法
Java中spring读取配置文件的几种方法如下:
一、读取xml配置文件
(一)新建一个java bean
package chb.demo.vo;
public class HelloBean {
private String helloWorld;
public String getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
}
(二)构造一个配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean id="helloBean" class="chb.demo.vo.HelloBean">
<property name="helloWorld">
<value>Hello!chb!</value>
</property>
</bean>
</beans>
(三)读取xml文件
1.利用
ApplicationContext context = new ("beanConfig.xml");
//这种用法不够灵活,不建议使用。
HelloBean helloBean = (HelloBean)context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
2.利用FileSystemResource读取
Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常。
二、读取properties配置文件
这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
我们还利用上面的HelloBean.java文件,构造如下beanConfig.properties文件:
helloBean.class=chb.demo.vo.HelloBean
helloBean.helloWorld=Hello!chb!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.来读取属性文件
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
reader = new (reg);
reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));
BeanFactory factory = (BeanFactory)reg;
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
(二)利用java.util.Properties读取属性文件
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
ip=192.168.0.1
port=8080
则,我们可以用如下程序来获得服务器配置信息:
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.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.(
this.getServletContext());
wac = WebApplicationContextUtils.getWebApplicationContext(
this.getServletContext());
JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
其中,jdbcTemplate为spring配置文件中的一个bean的id值。
这种用法比较灵活,spring配置文件在web中配置启动后,该类会自动去找对应的bean,而不用再去指定配置文件的具体位置。
10. springmvc中怎么从配置文件中读取信息
在使用hibernate或者spring的时候,我们往往通过配置文件配置数据库连接属性。但这次项目中并没有用到hibernate和spring,只用到了struts2。要如何实现通过读取文件配置获取属性值呢?
方式一:ResourceBundle这个类可是实现读取properties文件来获取值
在java中:
public class ResourceBundleReader {
public final static Object initLock = new Object();
private final static String PROPERTIES_FILE_NAME = "property";
private static ResourceBundle bundle = null;
static {
try {
if (bundle == null) {
synchronized (initLock) {
if (bundle == null)
bundle = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.CHINA);
}
}
} catch (Exception e) {
System.out.println("读取资源文件property_zh.properties失败!");
}
}
public static ResourceBundle getBundle() {
return bundle;
}
public static void setBundle(ResourceBundle bundle) {
bundle = bundle;
}
}
在.properties文件中:
driverName=com.mysql.jdbc.Driver
url=xxxxx/:3307/9zgame?
user=root
password=xxxxxx
文件名字为:property_zh.properties。后zh根据Locale.CHINA一致的,如果Locale.ENGLISH,则文件名为:property_en.properties
方式二:使用commons组件。