1

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

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
4

1 回答 1

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

您正在调用getBean()context显然是空的。

setApplicationContext()上下文只会在 Triangle bean 被构造之后,并且在Spring 调用它的方法之后才会被 Spring 初始化。只有这样,您才能调用getBean()上下文。

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

public class Triangle {

    private Point pointA;

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

    ...
}
于 2013-05-20T06:41:54.600 回答