Spring @Autowired usage

后端 未结 9 816
长发绾君心
长发绾君心 2020-12-04 04:51

What are the pros and cons of using @Autowired in a class that will be wired up by Spring?

Just to clarify, I\'m talking specifically about the

9条回答
  •  佛祖请我去吃肉
    2020-12-04 05:13

    For me here is what I like/dislike about Spring and auto-wiring.

    Pros:

    • Auto-wiring gets rid of nasty XML configuration.
    • Much easier to use annotations which allows you to inject directly using fields, setter methods, or constructors. Also allows you to annotate and 'qualify' your injected beans.

    Cons:

    • Using auto-wiring and annotations makes you dependent on Spring libraries where as with XML configuration you could chose to run with or without Spring. Like you said, you become tied to a DI framework.
    • At the same time I like being able to 'qualify' beans, to me this makes the code really messy. If you need to inject the same bean in multiple places, I've seen the same string name repeated all over. To me this seems to have the potential for errors.

    I've started using auto-wiring almost exclusively at work because we depend so much on Spring integration anyway that the dependency issue is moot. I worked on a Spring MVC project that used auto-wiring extensively and was a little hard to wrap my head around.

    I think auto-wiring is an acquired taste, once you get used to it you realize how powerful, easy, and much less of a headache it is to work with than the XML configuration.

提交回复
热议问题