benefit of @Autowired annotation in Java

后端 未结 4 1682
庸人自扰
庸人自扰 2021-02-14 01:01

Maybe, because of my wrong English, I couldn\'t understand the benefit of using @Autowired annotation.

According to the tutorial we can simplify the first(I.) case to se

相关标签:
4条回答
  • 2021-02-14 01:44

    @Autowired is spring-specific. @Inject is the standard equivallent. It is an annotation that tells the context (spring, or in the case of @Inject - any DI framework) to try to set an object into that field.

    The compiler has nothing to do with this - it is the DI framework (spring) that instantiates your objects at runtime, and then sets their dependencies at the points you have specified - either via XML or via an annotation.

    I agree it is a possible scenario for a DI framework to try to inject dependencies into all fields, even if they are not annotated. (And if you want to exclude a particular field, to annotate it). But they chose the other strategy (configuration-over-convention). By the way:

    • if using xml config and choose some form of autowiring, the dependencies of the bean will be automatically autowired without the need to specify anything
    • you can specify per-context autowiring settings.
    0 讨论(0)
  • 2021-02-14 01:46

    @Autowired tells Spring to find a bean of the declared type and wire in that bean, rather than requiring an explicit lookup by bean name. It can, under certain circumstances, make configuring applications easier if you only have one implementation of your types in a given Spring context.

    0 讨论(0)
  • 2021-02-14 01:55

    When the server bootstraps itself. It finds

     <context:annotation-config />
    

    in the application context and then goes through the classes defined in the contexts. If there are any beans that are autowired, it injects that into the class by referring the context file.

    Basically, it promotes convention over configuration. That's what most frameworks do these days to reduce the development time.

    0 讨论(0)
  • 2021-02-14 01:56

    the @Autowired Spring annotation tells Spring to for a bean named 'empDao' and inject it into the EmpManager class, without you having to add the empDao bean as a property in your spring config file.

    0 讨论(0)
提交回复
热议问题