@Autowired in @Service?

Spring will first create the bean instance, then inject the beans. You're trying to access to the injected bean when the current bean is created, thus the bean will be null. That's default behavior.

If you want/need to execute any logic after creating the bean, use @PostConstruct decorated method, which is invoked after the bean has been created and all the dependencies injected. Here's a sample:

@Service
public class Searcher extends Thread implements ISearcher {

    @Autowired
    protected ISessionProvider sessionProvider;

    public Searcher() {
        //nothing should be here...
    }

    @PostConstruct
    public void init() {
        sessionProvider.doSomeStuff();
    }
}

Spring can only do dependeny injection after the bean has been constructed. You are calling the method in the constructor and at that point the ISessionProvider hasn't been injected yet and hence it is null which in turn leads to a nice NullPointerException.

You have 2 solutions

  1. Move the code from the constructor to a method annotated with @PostConstruct
  2. Change the default no-arg constructor to take an argument and use that to do dependeny injection instead of the @Autowired field.

Solution 1: move that code to a method annotated with @PostConstruct.

@Service
public class Searcher extends Thread implements ISearcher {
    @Autowired
    protected ISessionProvider sessionProvider;
    ...
    public Searcher() {}

    @PostConstruct
    public void init() {
        sessionProvider.doSomeStuff();
    }

Solution 2: Use constructor based dependency injection.

@Service
public class Searcher extends Thread implements ISearcher { 

    protected final ISessionProvider sessionProvider;

    @Autowired
    public Searcher(ISessionProvider sessionProvider) {
        this.sessionProvider=sessionProvider;
        sessionProvider.doSomeStuff();
    }
}

Tags:

Java

Spring