I am trying to inject factory to my application. For this I have created
Factory: DrawShapeFactory.java
public class DrawShapeFactory implements Factory<Shape>
{
public void execute(Shape s)
{
s.draw();
}
@Override
public void dispose(Shape shape)
{
// TODO Auto-generated method stub
}
@Override
public Shape provide()
{
// TODO Auto-generated method stub
return null;
}
Create Binder class: DrawShapeBinder.java
public class DrawShapeBinder extends AbstractBinder
{
@Override
protected void configure()
{
bind(DrawShapeFactory.class).to(DrawShapeFactory.class);
}
}
ResourceConfig file
public class App extends ResourceConfig
{
public App()
{
packages("com.icube.rest.authorize","com.icube.rest.test");
register(new DrawShapeBinder());
}
}
Having classes:
Shape.java
public class Shape
{
public void draw()
{
}
}
Circle.java
public class Circle extends Shape
{
public void draw()
{
System.out.println("===>>> Circle draw <<<<========");
}
}
Tringle.java
public class Tringle extends Shape
{
public void draw() {
System.out.println("===>>> Tringle draw <<<<========");
}
}
Square.java class having
@inject
public class Square extends Shape
{
@Inject DrawShapeFactory drawShapeFactory;
public void drawTest()
{
System.out.println("===>>> Square draw <<<<========");
drawShapeFactory.execute(new Circle());
}
}
My Resource code is
@SuppressWarnings({"cast"})
@Path("/auth")
public class AuthResource
{
//inject here
@Inject DrawShapeFactory drawShapeFactory;
@POST
@Path("test")
public Detail test()
{
Shape shape1 = new Circle();
shape1.draw();
Shape shape2 = new Tringle();
shape2.draw();
drawShapeFactory.execute(new Tringle());
Square s= new Square();
s.drawTest();
}
I am getting output with error like:
===>>> Circle draw <<<<========
===>>> Tringle draw <<<<========
===>>> Tringle draw <<<<========
===>>> Square draw <<<<========
java.lang.NullPointerException
com.icube.rest.test.Square.drawTest(Square.java:11)
Why I am getting NULL
in Square.java
class for @Inject DrawShapeFactory drawShapeFactory; at drawShapeFactory.execute(new Circle());
line ?
Inject
is working fine at resource layer but inside any other class it is giving me NULL exception
.
What am I doing wrong ?
Thanks :-)