问题描述
我看到一些奇怪的行为,我希望这里有人可以对这个问题有所启发。
I'm seeing some odd behavior, I was hoping someone here can shine some light on the issue.
让我先介绍一下我的设置。首先,一个简单的数据对象
Let me start by describing my setup. First, a simple data object
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();
}
}
所有这一切都很有效。我运行测试,我看到了我期望的输出。但后来我将一个扳手扔进方向盘并修改AbstractTestConfig,如下所示。
All of this works great. I run the test, I see the output I expect. But then I throw a spanner into the wheel and modify AbstractTestConfig to look as follows.
@Configuration
public class AbstractTestConfig {
@Autowired ConfigInterface conf;
@Bean Apple myTestApple() {
return conf.getApple();
}
// NEW CODE
@Bean CustomScopeConfigurer scopeConfigurer() {
return new CustomScopeConfigurer();
}
}
突然间 @Autowired
对象 conf
在需要构造 Apple
bean时为null。
And all of a sudden the @Autowired
object conf
is null when it is required to construct the Apple
bean.
更奇怪的是,如果我将 CustomScopeConfigurer
bean移动到 TestConfig
class,然后它可以工作。
Even more odd, if I move the CustomScopeConfigurer
bean to the TestConfig
class, then it works.
是否有我不了解的范围或 CustomScopeConfigurer
特别是对象?
Is there something I don't know about scopes or the CustomScopeConfigurer
object in particular?
推荐答案
从Spring @Bean复制:
Copied from Spring @Bean javadoc:
必须特别考虑返回Spring BeanFactoryPostProcessor(BFPP)类型的@Bean方法。由于BFPP对象必须在容器生命周期的早期实例化,因此它们可能会干扰@Configuration类中@Autowired,@ Value和@PostConstruct等注释的处理。要避免这些生命周期问题,请将BFPP返回@Bean方法标记为静态。例如:
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 ...
}
这篇关于Spring的JavaConfig和CustomScopeConfigurer问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!