我正在尝试在单例类中注入原型对象..
public class Triangle implements ApplicationContextAware{
private Point pointA;
private ApplicationContext context=null;
Point point=(Point)context.getBean("pointA",Point.class);
public void draw(){
System.out.println("The prototype point A is ("+point.getX()+","+point.getY()+")");
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context=context;
}
}
我使用坐标x和y创建了一个Point java文件。
当我尝试编译上面的代码时,我得到以下错误
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [Spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.david.shape.Triangle]: Constructor threw exception; nested exception is java.lang.NullPointerException
答案 0 :(得分:1)
private ApplicationContext context=null;
Point point=(Point)context.getBean("pointA",Point.class);
您在getBean()
上呼叫context
,显然是空。
只有在构造了Triangle bean之后,Spring才会初始化上下文,并且在Spring调用其setApplicationContext()
方法之后。只有这样,您才可以在上下文中调用getBean()
。
public class Triangle {
private Point pointA;
@Autowired
public Triangle(@Qualifier("pointA") Point pointA) {
this.pointA = pointA;
}
...
}