猿问

spring boot:如何从应用程序属性配置数据源

我想下面的代码值:DriverClassName,Url,Username,Password从读取application.properties文件,该怎么做?我正在使用 Spring Boot、Mysql、Hibernate 和 Spring Rest。


数据源配置文件


    //This is working fine with inline value specified as below (DriverClassName, Url,Username,Password

    @Configuration

    @EnableTransactionManagement

    @EnableJpaRepositories(basePackages = "com.nouhoun.springboot.jwt.integration.repository")

    public class DatasourceConfig {


        @Bean

        public DataSource datasource() throws PropertyVetoException {

               final DriverManagerDataSource dataSource = new DriverManagerDataSource();

               dataSource.setDriverClassName("com.mysql.jdbc.Driver");

               dataSource.setUrl("jdbc:mysql://localhost:3306/fdb?createDatabaseIfNotExist=true");

               dataSource.setUsername("root");

               dataSource.setPassword("");

               return dataSource;

    }

   ....

   ....

   ....


蛊毒传说
浏览 140回答 2
2回答

温温酱

一旦你定义数据源属性application.properties中@SpringBootApplication它会自动配置datasource,这样你就可以删除DataSource configuration。但是如果你想自定义你的数据源配置,那么下面应该Environment可以让你访问属性:@Configuration@PropertySource(value= {"classpath:application.properties"})public class DatasourceConfig {    @Autowired    Environment environment;    @Bean    public DataSource datasource() throws PropertyVetoException {        final DriverManagerDataSource dataSource = new DriverManagerDataSource();        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));        dataSource.setUrl(environment.getProperty("spring.datasource.url"));        dataSource.setUsername(environment.getProperty("spring.datasource.username"));        dataSource.setPassword(environment.getProperty("spring.datasource.password"));        return dataSource;    }}或者,如果您不想通过 访问属性Environment,则可以通过访问@Value  @Value("${spring.datasource.driver-class-name}")    private String driverName;    @Value("${spring.datasource.url}")    private String url;    @Value("${spring.datasource.username}")    private String userName;    @Value("${spring.datasource.password}")    private String password;    @Bean    public DataSource datasource() throws PropertyVetoException {        final DriverManagerDataSource dataSource = new DriverManagerDataSource();        dataSource.setDriverClassName(driverName);        dataSource.setUrl(url);        dataSource.setUsername(userName);        dataSource.setPassword(password);        return dataSource;    }

浮云间

似乎您忘记在 pom.xml 或 build.gradle 中添加依赖项,或者如果您已经添加,则您的构建没有该依赖项(运行mvn clean install)<dependency>&nbsp; &nbsp; <groupId>mysql</groupId>&nbsp; &nbsp; <artifactId>mysql-connector-java</artifactId>&nbsp; &nbsp; <version>6.0.6</version></dependency>请添加并重试
随时随地看视频慕课网APP

相关分类

Java
我要回答