我有以下课程:
@ConfigurationProperties
public class Database {
...
@Value("${database.driver-class-name}")
public void setDriverClassName(String driverClassName) {
...
}
在build.gradle
中有以下依赖项:
dependencies {
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-configuration-processor')
在application.properties
中有以下一行:
database.driver-class-name=com.mysql.jdbc.Driver
在测试类上有以下注释:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(DatabaseTest.Context.class)
@EnableConfigurationProperties
public class DatabaseTest {
@Configuration
public static class Context {
@Bean
public Database database() {
Database ans = new Database();
return ans;
}
}
@Autowired
public Database database;
并且它既没有从属性文件中注入属性也没有发誓带有一些错误消息。
它还想要什么?
从属性文件中注入属性的必要条件是什么?
UDPATE
示例存储库:https://github.com/dims12/MinimalRequrementsToInjectPropertiesFromFile
答案 0 :(得分:2)
您班上的@configurationProperties
应该有@Bean
或@Component
注释,以便为弹簧注入属性值。有关属性的更多信息,请参见here
@ConfigurationProperties
@Component // or @Bean
public class Database {
答案 1 :(得分:1)
Sorry, found an answer myself.
In the case of Spring Boot, a context configuration class is usually annotated with @SpringBootApplication
which causes many things, including automatic finding an wiring of property files. This is invoked by @EnableAutoConfiguration
, which is contained inside former annotation.
In my case, I have annotated context configuration class with plain-Spring @Configuration
annotation only, because I was in JUnit
test and thought it is not an application. In this case I was to add @EnableAutoConfiguration
explicitly.
Probably I was also allowed to annotate context configuration class with @SpringBootApplication
, but I didn't test it.
@EnableConfigurationProperties
was not needed at all. Also no need for @ConfigurationProperties
, and AutowiredAnnotationBeanPostProcessor
.