春ブーツ:アプリケーションのプロパティからデータソースを設定する方法

そして、:

私は、コード値を下回るたい:DriverClassNameUrlUsernamePasswordから読み取ることがapplication.propertiesのファイル、それを行う方法?私は春ブーツ、Mysqlの、Hibernateと春の休憩を使用しています。

DatasourceConfig.java

    //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;
    }
   ....
   ....
   ....
kj007:

あなたがデータソースプロパティ定義した後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;
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=190233&siteId=1