我倾向于使用spring boot 2.0,我使用@Value注释与早期版本相同,但它在@Configration注释中不起作用。
application.yml
test:
a: test
TestApplication.java
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(TestApplication.class, args);
System.out.println(context.getEnvironment()
.getProperty("test.a"));//got test
}
}
TestConfigration.java
@Configuration
public class TestConfigration{
@Value("${test.a}")
String a;
@Bean
public Bean getBean(){
System.out.println(a);//there!!!the a is NULL!!! WHY?
return new Bean();
}
}
TestController.java
@RestController
@RequestMapping("/")
public class TestController{
@Value("${test.a}")
String a;
@RequestMapping("/")
public String test(){
return a;//got test
}
}
为什么?
答案 0 :(得分:0)
嗯......问题的代码没有问题,它有效。
我在春季启动开始时忽略了警告日志:
2018-03-26-21:21:27 WARN [org.springframework.context.annotation.ConfigurationClassPostProcessor] - Cannot enhance @Configuration bean definition 'TestConfigration' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
它是因为我用@Bean注册org.mybatis.spring.mapper.MapperScannerConfigurer但是错过了静态关键字,如果在相同的配置类中使用了BeanFactoryPostProcessor寄存器和@Value的实现,那么它是必要的
我不知道它并且我曾经错过太久,我没有找到它,因为db配置和mybatis配置在我过去的项目中不在同一个类中。
感谢@ailav和@Impulse The Fox,请原谅我奇怪的英语:)