0

Spring @Autowired

I have a doubt on Spring @Autowired annotation.Please Help...

In Spring mvc ,when I tried @Autowired in this order

Controller--->Service--->Dao

ie,In Controller I autowired Service Class Object , In Service Class Autowire Dao Object.

This Injection chain works perfectly.

Similliarly In strutrs2+Spring ,I applied @Autowired Annotation in this way

Action--->Service-->Dao

This Injection chain also works fine.

If I call a funtion from outside this chain (eg:Custom Taglib class (from jsp)) to funtion in Service class Then in this Service class the Autowired dao object is null(ie,this call braks the chain).

My questions is

Is this @Autowired works in a Injection chain Only?

SRK
  • 130
  • 1
  • 9

1 Answers1

1

Beans that have @Autowired fields only have them set if they are sent through the Spring Bean Postprocessor -- that is, like you said, if you autowire them yourself. That is a big reason that constructor injection is much more preferred than field injection. Instead of doing

@Service
public class MyService {
     @Autowired
     private MyDao dao;

     ...
}

you should do

@Service
public class MyService {
    private final MyDao dao;

    @Autowired
    public MyService(MyDao dao) {
        this.dao = dao;
    }
}

That way, when you're in a situation where you can't rely on a service to be post-processed (as in your case of using the jsp tag library), you can simply instantiate a new instance with a MyDao object and be on your merry way.

Josh Ghiloni
  • 1,260
  • 8
  • 19
  • Thank you very much for your answer @Josh . But in Theory , spring appliCationContext loaded on startup and loaded every beans and all are live.then why Autowired injection working failed even the beans are live.? – SRK Sep 03 '16 at 12:42
  • The question is, how is the function that you're calling (your custom taglib class method, for example) getting the instance of the service bean that *it's* calling? If it's saying `new MyService()` then those will not have fields injected because they haven't been through the postprocessor. The applicationContext doesn't autowire classes themselves, as it can't do that because injected fields aren't static. It injects on instances, so my guess is your taglib isn't autowiring the service instance to call. It's instantiating one itself. – Josh Ghiloni Sep 03 '16 at 14:58
  • you r right..my taglib class uses new Myservice().taglib classes are not supported [link](http://stackoverflow.com/questions/28304546/enable-jsp-custom-taglib-to-use-spring-service-beans) . – SRK Sep 03 '16 at 17:00