我看到了一些奇怪的行为,我希望这里有人能对这个问题有所了解。
让我从描述我的设置开始。一、简单的数据对象
public class Apple {
private String name;
public Apple withName(String name) {
this.name = name;
return this;
}
public String getName() {
return name;
}
}
还有一个测试类..
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfig.class})
public class AppleTest {
@Autowired private Apple apples;
@Test
public void simpleTest() {
System.out.println("OBJ: "+apples);
}
}
配置如下
@Configuration
public interface ConfigInterface {
public Apple getApple();
}
有一个实现类
@Configuration
@Import(AbstractTestConfig.class)
public class TestConfig implements ConfigInterface {
public Apple getApple() {
return new Apple().withName("Granny apples");
}
}
带有配置依赖...
@Configuration
public class AbstractTestConfig {
@Autowired ConfigInterface conf;
@Bean Apple myTestApple() {
return conf.getApple();
}
}
所有这些都很好用。我运行测试,我看到了我期望的输出。但随后我将 Spanner 扔进方向盘并修改 AbstractTestConfig 如下所示。
@Configuration
public class AbstractTestConfig {
@Autowired ConfigInterface conf;
@Bean Apple myTestApple() {
return conf.getApple();
}
// NEW CODE
@Bean CustomScopeConfigurer scopeConfigurer() {
return new CustomScopeConfigurer();
}
}
当需要构造 Apple
bean 时,@Autowired
对象 conf
突然为空。
更奇怪的是,如果我将 CustomScopeConfigurer
bean 移动到 TestConfig
类,那么它就可以工作了。
我对范围或 CustomScopeConfigurer
对象有什么不了解的地方吗?
最佳答案
复制自 Spring @Bean javadoc :
BeanFactoryPostProcessor-returning @Bean methods
Special consideration must be taken for @Bean methods that return Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired, @Value, and @PostConstruct within @Configuration classes. To avoid these lifecycle issues, mark BFPP-returning @Bean methods as static. For example:
@Bean
public static PropertyPlaceholderConfigurer ppc() {
// instantiate, configure and return ppc ...
}
By marking this method as static, it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in BFPP cases, as they are not typically referenced by other @Bean methods. As a reminder, a WARN-level log message will be issued for any non-static @Bean methods having a return type assignable to BeanFactoryPostProcessor.
关于java - Spring 的 JavaConfig 和 CustomScopeConfigurer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14942304/