-1

i have @Autowired the sessionFactory bean in my class and then I instantiated that class at runtime and when I call the method, it is throwing a nullpointer exception. I don't know what I'm missing in my code. It compiles successfully and when i run it, it's throwing a nullpointer exception. Can someone please help me?

here is my class:

public class InstantiateSampleAutowire{

    SampleAutoWire sampleAutowire = new SampleAutowire();
    sampleAutowire.getSomeData();

}

@Component
public class SampleAutowire{

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public void getSomeData(){

        getCurrentSession().createQuery(SQLQuery);

    }

}
arn-arn
  • 1,328
  • 1
  • 21
  • 31
  • Seems you're not experienced with dependency injection. See [this article](http://www.tutorialspoint.com/spring/spring_dependency_injection.htm). Since you're instantiating the object in your code, Spring has no way of capturing that and injecting the dependency. – xathien Oct 14 '15 at 20:45
  • Possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – kryger Oct 14 '15 at 21:33

2 Answers2

0

You should inject SampleAutowire into InstantiateSampleAutowire inorder to let the spring-context handle your instances.

public class InstantiateSampleAutowire {
   @Autowired
   SampleAutoWire sampleAutowire;
   ...
}

You get a better explination if you read this post: Why is my Spring @Autowired field null?

Community
  • 1
  • 1
Richard
  • 137
  • 4
-1

If it is a real code then some configuration is missing.

public class InstantiateSampleAutowire{

SampleAutoWire sampleAutowire = new SampleAutowire();
sampleAutowire.getSomeData();

}

In order to use a component (SampleAutowire) you need that the invoker class (InstantiateSampleAutowire) was in the same spring contex o the invoker obtains the Spring context.

Yo coud do this by Adding @Component @Component public class InstantiateSampleAutowire{

and then @Autowire to the instance

@Autowired SampleAutoWire sampleAutowire;

reos
  • 8,766
  • 6
  • 28
  • 34