spring内部类的实例化
示例代码
/**
* 内部类的实例化
*/
public class H {
class J{
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// context.register(H.class);
context.register(J.class);
context.refresh();
context.getBean(J.class);
}
}
直接对对象J进行注册bean,会出现异常
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'h.J'
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.inside.H'
跟踪spring源码发现,在spring实例化对象时,AbstractAutowireCapableBeanFactory类中:
会有一个推断类的构造方法的过程
这里推断出内部类J有一个参数为类H的构造方法,因为为J是H的一个成员变量
综上所知,因为我们并没有注册类H到工厂,实例化内部类J的时候,找不到工厂中类H的bean,所以就抛出了异常
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.inside.H'
解决异常:
1.只需要在内部类中加入含参数H的构造方法,并且把H注册给spring容器
2.把J定义成为一个静态的内部类;这样就不需要H的对象就能实例化J
public class H {
static class J{
}
}