ApplicationContextAware在singleton对象中注入原型对象

时间:2013-05-20 05:44:10

标签: java spring

我正在尝试在单例类中注入原型对象..

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

1 个答案:

答案 0 :(得分:1)

private ApplicationContext context=null;
Point point=(Point)context.getBean("pointA",Point.class);

您在getBean()上呼叫context,显然是空。

只有在构造了Triangle bean之后,Spring才会初始化上下文,并且在Spring调用其setApplicationContext()方法之后。只有这样,您才可以在上下文中调用getBean()

顺便说一句,你不是在这里做依赖注入。你正在进行依赖查找,这正是像Spring这样的依赖注入框架被用来避免的。要注意你的观点,只需做

public class Triangle {

    private Point pointA;

    @Autowired
    public Triangle(@Qualifier("pointA") Point pointA) {
        this.pointA = pointA;
    }

    ...
}