java - ApplicationContextAware injecting the prototype object in the singleton object -
i trying inject prototype object in singleton class..
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 ("+point.getx()+","+point.gety()+")"); } @override public void setapplicationcontext(applicationcontext context) throws beansexception { this.context=context; } } i created point java file co-ordinates x , y..
when tried compile above code following errors
exception in thread "main" org.springframework.beans.factory.beancreationexception: error creating bean name 'triangle' defined in class path resource [spring.xml]: instantiation of bean failed; nested exception org.springframework.beans.beaninstantiationexception: not instantiate bean class [com.david.shape.triangle]: constructor threw exception; nested exception java.lang.nullpointerexception
private applicationcontext context=null; point point=(point)context.getbean("pointa",point.class); you're calling getbean() on context is, obviously, null.
the context initialized spring after triangle bean has been constructed, , after setapplicationcontext() method has been called spring. then, can call getbean() on context.
btw, you're not doing dependency injection here. you're doing dependency lookup, dependency injection frameworks spring used avoid. inject point, do
public class triangle { private point pointa; @autowired public triangle(@qualifier("pointa") point pointa) { this.pointa = pointa; } ... }
Comments
Post a Comment