Search code examples
javaspringapplicationcontext

Reading value from file into applicationContext.xml file


I have a spring based web application and in my application context xml file, I have defined a bean which has all the parameters to connect to database. As part of this bean, for one of the parameters, I have a password key, as shown in the below example and I wanted the value should come from a /vault/password file. This /vault/password is not part of the project/application. This /vault/password will be there in host machine by default.

What is the syntax in applicationContext.xml bean definition, to read a value from a file outside of application context.

<bean class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" id="dataSource">
    <property name="url" value="jdbc:postgresql://postgres:5432/" />
    <property name="username" value="postgres" />
    <property name="password" value="/vault/password" />
</bean>

Solution

  • Something like this is probably your best bet:

    How to correctly override BasicDataSource for Spring and Hibernate

    PROBLEM:

    Now I need to provide custom data source based on server environment (not config), for which I need to calculate driverClassName and url fields based on some condition.

    SOLUTION:

    Create a factory (since you need to customize only the creation phase of the object, you don't need to control the whole lifetime of it).

     public class MyDataSourceFactory {
        public DataSource createDataSource() {
            BasicDataSource target = new BasicDataSource();
            if (condition) {
                target.setDriverClassName("com.mysql.jdbc.Driver");                
                target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true"); 
            } else { ... }
            return target;
        }
    }
    

    In your case, your customization would do some I/O to set target.password.