2 回答
TA贡献1752条经验 获得超4个赞
一旦你定义数据源属性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;
}
TA贡献1829条经验 获得超4个赞
似乎您忘记在 pom.xml 或 build.gradle 中添加依赖项,或者如果您已经添加,则您的构建没有该依赖项(运行mvn clean install)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
请添加并重试
添加回答
举报