Anas Hadhri
Anas Hadhri

Reputation: 179

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 ?

Upvotes: 0

Views: 3169

Answers (2)

Antal Attila
Antal Attila

Reputation: 618

@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.

Upvotes: 0

Jesper
Jesper

Reputation: 206996

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.

Upvotes: 1

Related Questions