Reputation: 12283
I have a Spring 4 MVC Servlet, which uses JPA and spring-orm to connect to the database. My applicationContext.xml
file contains the following:
<util:map id="persistenceUnitConfiguration">
<entry key="javax.persistence.logging.level" value="INFO" />
<entry key="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<entry key="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/DATABASE" />
<entry key="javax.persistence.jdbc.user" value="USERNAME" />
<entry key="javax.persistence.jdbc.password" value="PASSWORD" />
<entry key="eclipselink.weaving" value="false" />
</util:map>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="myPersistenceUnit" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="packagesToScan" value="my.package.entities" />
<property name="jpaPropertyMap" ref="persistenceUnitConfiguration" />
</bean>
The application is packaged as a WAR. I want to somehow configure the DATABASE, USERNAME, and PASSWORD values, such that I can distribute the WAR and nobody has to touch it. Only thing to do would be to edit a configuration file somewhere.
What is the best approach for doing so?
Can I somehow set the jpaPropertyMap programmatically during boot of my webapp and read it from a configuration file at a fixed location?
Upvotes: 1
Views: 270
Reputation: 85779
Create a properties file like database.properties:
db.user=youruser
db.password=yourpassword
Then in your Spring application config file, add
<context:property-placeholder location="classpath:my/package/config/database.properties" />
Now you can access to the properties using expression language syntax:
<bean ...>
<property name="dbUser" value="${db.user}" />
<property name="dbPassword" value="${db.password}" />
</bean>
If you're using annotation config, then use
@Component
public class YourBean {
@Value( "${db.user}" )
private String dbUser;
@Value( "${db.password}" )
private String dbPassword;
}
Applied to your case, it would be (similar for more fields)
<util:map id="persistenceUnitConfiguration">
<entry key="javax.persistence.logging.level" value="INFO" />
<entry key="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<entry key="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/DATABASE" />
<entry key="javax.persistence.jdbc.user" value="${db.user}" />
<entry key="javax.persistence.jdbc.password" value="${db.password}" />
<entry key="eclipselink.weaving" value="false" />
</util:map>
If your properties file is outside classpath, use file:
instead:
<context:property-placeholder location="file:/path/to/your/database.properties" />
Upvotes: 1