简体   繁体   中英

load dataSource from application.properties

I am using Spring + Hibernate for a school project.

Everything is working, i am able to get data from the database but i have a question about the database settings.

Is it possible to replace the getDataSource method for a config file? Example application.properties.

How can I implement it in my config file? And is there a specified location for config files?

This is my AppConfig.java

package com.exstodigital.photofactory;

import com.exstodigital.photofactory.dao.impl.UserDAOImpl;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
public class AppConfig {
    @Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);

        // Models
        sessionBuilder.scanPackages("com.exstodigital.photofactory.model");

        return sessionBuilder.buildSessionFactory();
    }

    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("********");
        dataSource.setUsername("********");
        dataSource.setPassword("********");

        return dataSource;
    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);
    }
}

Of course you can

Try something like

@Value("${spring.datasource.url}")
    private String jdbcURl;

@Value("${spring.datasource.username}")
    private String dbUsername;

@Value("${spring.datasource.password}")
    private String dbPassword;

@Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "your package" });
        return sessionFactory;
    }

@Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(jdbcURl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource

}

So your application.properties will have the following properties:

spring.datasource.url = {whatever you want to put}
spring.datasource.username = {Your username}
spring.datasource.password = {Your password}

Update your server.xml to have the following lines, it is same like what you are doing in the getDataSource() but datasource is configured at the server level.

<Resource name="jdbc/MyDB" 
      global="jdbc/MyDB" 
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver" 
      url="jdbc:mysql://localhost:3306/UserDB" 
      username="pankaj" 
      password="pankaj123"        
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>

in your getDataSource just pull this datasource using the following lines of code and return it.

DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyLocalDB");

ref : http://www.journaldev.com/2513/tomcat-datasource-jndi-example-java

yes it can be done.

first make a config file:give it a name in my case it is prop.properties and provide all details in key value pairs

host=127.0.0.1
port=****
dbuser=****
dbpwd=****
dbname=****

then create a property object and file input stream

public static Properties prop = new Properties();
    static InputStream input = null;

load the property file by providing it's location. i have my file in /opt folder

static{
            try {                 
                input = new FileInputStream("/opt/prop.properties");
                prop.load(input);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

now fetch all the property by providing the keys

prop.getProperty("host");
prop.getProperty("port");
prop.getProperty("dbuser");
prop.getProperty("dbpwd");
prop.getProperty("dbname");

you can keep the file in the desired location. but sure to provide the relative path in the program.

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