spring boot 1.2.5 @Configuration @Autowired annotation null?

时间:2015-07-14 09:50:52

标签: java spring spring-boot

PrimaryDatasourceProperties.java获取application.properties内容,这是对的。

方法DatasourceConfig.java内的{p> @Bean ... primaryDataSource ()没有primaryDatasourcePropertiesprimaryDatasourceProperties null ,这是@Autowired注入的,它总是一个问题

请问是什么原因?

顺便说一句:

DemoApplication.java尝试加入EnableAutoConfigurationPrimaryDatasourceProperties.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);
    }
}

1 个答案:

答案 0 :(得分:1)

您必须将注释@EnableConfigurationProperties添加到DemoApplication或您的配置类。请参阅manual about that topic