我正在尝试以编程方式在jUnit测试中将内部bean添加到我的应用程序上下文中。我不想通过给bean加上注释来污染我的上下文,@Component
因为它将影响在同一上下文中运行的所有其他测试。
public class PatchBaseImplTest extends TestBase{
/**
* Sample test patch to modify the schema
*/
public class SchemaUpdatePatch extends PatchBaseImpl {
public SchemaUpdatePatch(){
super();
}
@Override
public void applyPatch() throws Exception {
}
};
@Before
public void setUp(){
// add patch to context
beanRegistry.registerBeanDefinition("SchemaUpdatePatch", SchemaUpdatePatch.class, BeanDefinition.SCOPE_PROTOTYPE);
schemaPatch = (Patch)applicationContext.getBean("SchemaUpdatePatch", SchemaUpdatePatch.class);
}
}
其中registerBeanDefinition定义为:
public void registerBeanDefinition( String name, Class clazz, String scope){
GenericBeanDefinition definition = new GenericBeanDefinition();
definition.setBeanClass(clazz);
definition.setScope(scope);
definition.setAutowireCandidate(true);
definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
registry.registerBeanDefinition(name, definition);
}
我可以看到Bean defn已添加到应用程序上下文中,但是当我尝试使用appContext.getBean()检索Bean时,Spring抛出错误,该类缺少构造函数:
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ia.system.patch.PatchBaseImplTest$SchemaUpdatePatch]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ia.system.patch.PatchBaseImplTest$SchemaUpdatePatch.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
... 35 more
Caused by: java.lang.NoSuchMethodException: com.ia.system.patch.PatchBaseImplTest$SchemaUpdatePatch.<init>()
at java.lang.Class.getConstructor0(Class.java:2800)
at java.lang.Class.getDeclaredConstructor(Class.java:2043)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
... 36 more
我尝试将默认构造函数添加到SchemaUpdatePatch类,但这似乎无关紧要。
但是,如果我用@Component对其进行注释,而不是通过编程将其添加到上下文中,然后尝试通过applicationContext.getBean()访问它,则它可以正常工作。
以编程方式将此bean添加到applicationContext的正确方法是什么?我的GenericBeanDefinition错误吗?我是否缺少某些东西来指定构造函数是什么?
写这篇文章实际上是宣泄的。帮助我找到我的错误/错误。必须使内部类为Static或Spring无法实例化它。希望这可以在将来对其他人有所帮助。
IE:
/**
* Sample test patch to modify the schema
*/
static public class SchemaUpdatePatch extends PatchBaseImpl {
public SchemaUpdatePatch(){
super();
}
@Override
public void applyPatch() throws Exception {
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句