gpt4 book ai didi

java - ApplicationContextAware 在单例对象中注入(inject)原型(prototype)对象

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:24 25 4
gpt4 key购买 nike

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

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;

}
}

我创建了一个 Point java 文件,坐标为 x 和 y..

当我尝试编译上面的代码时,出现以下错误

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

最佳答案

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

您正在对 context 调用 getBean(),这显然是 null。

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

顺便说一句,你在这里没有进行依赖注入(inject)。您正在执行依赖项查找,这正是 Spring 等依赖项注入(inject)框架所要避免的。要注入(inject)您的观点,只需执行

public class Triangle {

private Point pointA;

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

...
}

关于java - ApplicationContextAware 在单例对象中注入(inject)原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16643277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com