Stereotype @autowired vs @inject


When to use @autowired ? Is your goal to inject a class? But for that would not be @inject ?

    private CreateTextMessageService service;

In this case the @autowired is being used in a property.

But in the following example, it is being used in a set function. What does @autowired do?


import org.springframework.beans.factory.annotation.Autowired;

public class Product {
   private Integer price;
   private String name;
   private Type type;
   public Integer getPrice() {
       return price;

   public void setPrice(Integer price) {
       this.price = price;
   public Type getType() {
       return type;
   public void setType(Type type) {
       this.type = type;
   public String getName() {
       return name;
   public void setName(String name) { = name;
asked by deluf 15.05.2017 в 06:02

2 answers


@Inject is part of the Java standard, belongs to the annotation collection JSR-330 .

@Autowired is the own annotation of Spring for dependency injection. This annotation is prior to the appearance of the standard, so Spring, to comply with it, also adopted the annotation @Inject .

They could be used almost indistinctly, but there are slight differences:

  • @Inject is handled exclusively by the JAVA EE platform, while @Autowired is handled by Spring.
  • The @Autowire notation has the default attribute required to true , while @inject does not have this element. This is important if, for example, we try to inject a Bean and the injection fails, @Autowired allows us to specify required = false , so the field will be null .
  • @Inject allows, instead of injecting a reference directly, inject a Provider . A Provider allows us, among other things, the injection of multiple instances of a Bean .

The usual recommendation is to try to follow the standard path and opt for @Inject for migrations and new projects, since it works perfectly integrated in Spring.

answered by 18.05.2017 в 10:40

Spring provides an "alternative" software framework to what is the Java Enterprise Edition.

It is really quite messy, because it is not two completely separate systems, but many times they end up combining. To put a couple of examples:

  • Spring normally uses Hibernate as ORM, but also provides a "bridge" layer so that Hibernate can be used as a JPA implementation.

  • On the other hand, I have also seen environments where JSF is used as frontend for an application that internally uses Spring .

So @Autowired is -saying it somewhat crudely- the equivalent of @Inject in Spring.

answered by 15.05.2017 в 18:47