为什么 bean 在 junit 测试期间被多次初始化?



你能帮我理解为什么会发生以下情况吗? 我有以下豆子:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class TestBean implements BeanPostProcessor {
public void init() {
System.out.println("Initialized!");
}
public void destroy() {
System.out.println("Destroyed!");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization");
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization");
return null;
}
}

具有以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="TestBean" init-method="init" destroy-method="destroy"/>
</beans>

以及以下 JUNIT 测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:beans1.xml"})
public class TestBeanTest {
@Autowired
private TestBean collectionBean;
@Test
public void testCollectionBean() {
}
}

现在,令我惊讶的是,如果我运行该单元测试,"postProcessBeforeInitialization"和"postProcessAfterInitialization"分别打印5次。原因是什么?在 bean 初始化期间,它们不应该只打印 1 次吗? 提前谢谢你!

回顾一下我的评论:

对 Bean 后处理器postProcessBeforeInitialization方法略TestBean更改:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization " + beanName);
return null;
}

并且可能的最小 Spring 依赖性:org.springframework:spring-context:5.0.2.RELEASE

代码的输出为:

postProcessBeforeInitialization org.springframework.context.event.internalEventListenerProcessor
postProcessBeforeInitialization org.springframework.context.event.internalEventListenerFactory
postProcessBeforeInitialization TestBeanTest

结论:豆子只经过后处理器的一次后处理,其余的都是Spring自己的豆子。你得到 5 而我只得到 3 的事实是我们使用的不同依赖项集。

另外,请注意,TestBean甚至不被认为是(打印的(,因为它不是 bean,而是一个 bean 后处理器。

我认为文档和方法签名应该可以帮助您理解问题。

工厂钩子,允许自定义修改新豆 实例,例如检查标记接口或用 代理

我建议你也打印出豆名。这将向您展示像 EventlistnerFactories 这样的 bean 和其他以编程方式注入 bean 的工厂方法。因此,在注入发生之前,对每个 bean 调用此方法,让您有机会在需要时代理或包装您的 bean。

最新更新