我希望从 application.properties 文件中读取以下代码值:DriverClassName
,Url
,Username
,Password
,如何要做到这一点?我正在使用Spring Boot,Mysql,Hibernate和Spring Rest。
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;
}
....
....
....
答案 0 :(得分:0)
似乎您忘记在pom.xml或build.gradle中添加依赖项,或者如果您已经添加了构建,则构建不具有该依赖项(运行 mvn clean install )
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
请添加并重试
答案 1 :(得分:0)
一旦您在application.properties
的{{1}}中定义了数据源属性,它将自动为您配置@SpringBootApplication
,因此您可以删除datasource
,但是仍然要自定义数据源配置,则下面的配置应与DataSource configuration
一起使用,以使您可以访问属性。
Environment
或id不想通过@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;
}
}
访问属性,可以通过Environmetn
@Value