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

Dan*_*Dan 6 java spring hibernate spring-boot

我想下面的代码值:DriverClassNameUrlUsernamePassword从读取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;
    }
   ....
   ....
   ....
Run Code Online (Sandbox Code Playgroud)

kj0*_*007 7

一旦你定义数据源属性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;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想通过 访问属性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;
    }
Run Code Online (Sandbox Code Playgroud)