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組件。