简体   繁体   中英

Spring dependency injection @Autowired VS dependency injection of an object without @Autowired

what is the main difference between injecting objects with @Autowired and injecting without it ? I know that spring will initialize the bean , but what it is really offering ?

There are several ways to configure Spring beans and inject dependencies using Spring. One way is by using constructor injection, where the constructor of your Spring bean has arguments which are the dependencies that should be injected:

@Component
public class MyBean {
    private final SomeDependency something;

    @Autowired
    public MyBean(SomeDependency something) {
        this.something = something;
    }
}

However, since Spring 4.3, it is not necessary anymore to use @Autowired on such a constructor (click link for Spring documentation). So you can write it without the @Autowired :

@Component
public class MyBean {
    private final SomeDependency something;

    public MyBean(SomeDependency something) {
        this.something = something;
    }
}

This will work exactly the same as the code above - Spring will automatically understand that you want the dependency to be injected via the constructor. The fact that you can leave out @Autowired is just for convenience.

So, to answer your question: there is no difference.

@Autowired (so the injection) in some situation cannot be used, an example is if your autowired bean not ready because of some async stuff but in the target bean you want to use that.

So in this situation do not use inject (@Autowired) it is better to inject the ApplicationContext and in the exact moment get your bean from there by name or by class (there is a lot off possibilities there).

You can consider the @Autowired with the @Lazy annotation too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM