简体   繁体   中英

Web app with Spring: how externalize properties file?

I've built a J2EE web app using Spring framework on server Tomcat, and my application needs to read some properties (like jdbs connection parameters, paths of folders etc...) which I need to be external. What I mean is that today I put the jar on the server. If in 2 years the connection DB parameters or the folders I want to use are going to change I don't want to redeploy the app, but just change the properties file.

What I have by now is a .properties file in the classpath, and a bean that reads it:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:database.properties"/>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="url" value="${jdbc.url}" />
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

database.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cheExport?useSSL=false
jdbc.username=root
jdbc.password=root

How can I accomplish my purpose?

If I remember well there is something I can do in the server xml, where I can specify that a certain folder contains properties file. But then how can I put the things together?

In this post Read properties file outside JAR file is asked the same question, but without using Spring, so I think it's not useful in my case

I also read that it's common to use spring boot in this cases, but I'm using Spring MVC

You use util properties. just show for you my sample code.

root-context.xml

<util:properties id="config"
    location="classpath:config/config.properties" />

<bean id="officeDataSource"
    class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
    <property name="driverClass" value="#{config['driverClass']}" />
    <property name="url" value="#{config['commonUrl']}" />
    <property name="username" value="#{config['username']}" />
    <property name="password" value="#{config['password']}" />
</bean>

config.properties

driverClass=org.mariadb.jdbc.Driver
commonUrl=jdbc:mariadb://123.345.563.16:3306/FACE_BOOK_DB?useUnicode=yes&amp;characterEncoding=UTF-8

username=id
password=pw

for you project structure image. exist resource(web-inf-classes-config) in your project.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM