PrimaryDatasourceProperties.java
获取application.properties
内容,这是对的。
DatasourceConfig.java
内的{p> @Bean ... primaryDataSource ()
没有primaryDatasourceProperties
,primaryDatasourceProperties
null ,这是@Autowired注入的,它总是一个问题
请问是什么原因?
顺便说一句:
DemoApplication.java
尝试加入EnableAutoConfiguration
和
PrimaryDatasourceProperties.java
尝试@Component
结果没有什么不同
以下是代码:
资源/ application.properties
datasource.primary.driver-class-name=com.mysql.jdbc.Driver
datasource.primary.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8
datasource.primary.username=root
datasource.primary.password=
com.demo.config.PrimaryDatasourceProperties.java
@ConfigurationProperties(prefix="datasource.primary")
public class PrimaryDatasourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
com.demo.config.DatasourceConfig.java
@Configuration
public class DatasourceConfig {
@Autowired
private PrimaryDatasourceProperties primaryDatasourceProperties;
@Bean
@Primary
public DataSource primaryDataSource() {
// primaryDatasourceProperties is null ?
}
}
com.demo.DemoApplication.java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
}
}
答案 0 :(得分:1)
您必须将注释@EnableConfigurationProperties
添加到DemoApplication或您的配置类。请参阅manual about that topic。