简体   繁体   中英

Best way to store database info externally in spring MVC app

I'm looking to distribute my web app to many different departments of the company i work for and i'm wondering what would be the best way of allowing each deployment to provide their own database instance. I am using Hibernate and the first deployment actually creates the database and imports tons of data in it but i'm looking for the cleanest, most reliable way of allowing the users to specify their own database URL and credentials. Currently my code has a hard coded reference for the database info :

public DataSource dataSource() 
{
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    try
    {
        dataSource.setDriverClass("net.sourceforge.jtds.jdbc.Driver");
        String hostName = InetAddress.getLocalHost().getHostName();
        dataSource.setJdbcUrl("jdbc:jtds:sqlserver://localhost:1433/MDHIS;InstanceName=ADT;sendUnicode=false");
        dataSource.setUser("sa");
        dataSource.setPassword("N0tY0urBu$1nes$");
    }
    catch (Exception ignored) {}
    return dataSource;
}

I read online that you cannot easily read a config file using a relative path from a web app (by all means please crush this myth if it is one) so i was thinking of using environment variables. I want this to be completely portable and work on Ubuntu as well as Windows so not sure how well that would work. I am using a 100% annotation based method so there is no XML file whatsoever and i intend it to stay that way.

Any suggestions?

Thanks!

Thanks for the help, i ended up annotating my configuration class with :

@PropertySource("classpath:config.properties")

I then placed said file in the java folder which is the base of the classpath. I put this in the file :

dbUrl=jdbc:jtds:sqlserver://localhost:1433/MDHIS;InstanceName=ADT;sendUnicode=false

I can now access the info in the code by doing :

dataSource.setJdbcUrl(environment.getProperty("dbUrl"));

Environment is a dependency that is autowired in my Hibernate config class.

Thanks!

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