You’ve probably copied @Autowired from sample code without really knowing what it does. Plenty of developers are in the same spot. Recent code often leaves it out entirely, which makes it even more confusing.

Here’s the short answer up front.

  • @Autowired is a marker that tells Spring to “find this dependency in the DI container by type and pass it in”
  • If a class has only one constructor, the usual modern practice is to leave it out
  • When a dependency isn’t injected and ends up null, the cause is almost always that you’re using an instance Spring didn’t create

The concept of DI itself is covered in What Is DI (Dependency Injection) in Spring Boot?, and the pros and cons of each injection style are covered in Comparing the Three Dependency Injection Methods. This article focuses on how the @Autowired annotation itself behaves and how to fix it when it doesn’t work.

What Is @Autowired?

@Autowired (org.springframework.beans.factory.annotation.Autowired) is an annotation that tells Spring to look up a Bean registered in the ApplicationContext by type and pass it automatically to a field, setter, or constructor.

Both the class receiving the dependency and the dependency itself must be Spring-managed Beans. A class without @Component, @Service, or a similar annotation isn’t managed by Spring at all, so @Autowired does nothing there. The role of @Component is explained in What Is @Component?.

jakarta.inject.Inject and @Resource work in a similar way, but in Spring Boot you’ll usually use @Autowired or the shorthand covered later in this article.

How @Autowired Injection Works

The injection itself is done by a class called AutowiredAnnotationBeanPostProcessor. When Spring creates a Bean, this class finds the places marked with @Autowired and resolves their dependencies. Here’s the flow as a diagram:

Bean生成開始(例: OrderService)
  │
  ├─ コンストラクタ注入 … インスタンス化と同時に引数を解決して渡す
  │
  ▼
インスタンス化完了
  │
  ├─ AutowiredAnnotationBeanPostProcessor が @Autowired のフィールド・セッターを検出
  │
  ▼
型で候補Beanを検索(例: PaymentClient型のBean)
  ├─ 1件 → そのまま注入
  ├─ 複数 → @Primary / @Qualifier / パラメータ名で1つに絞る
  │          絞れなければ NoUniqueBeanDefinitionException
  └─ 0件 → required=true(デフォルト)なら NoSuchBeanDefinitionException

The key thing to remember is the order: constructor injection happens during instantiation, while field and setter injection happen after instantiation. This matters later in the section on why values end up null.

The detailed rules for choosing between multiple candidates are covered in Choosing Between @Qualifier and @Primary.

Three Ways to Use @Autowired

Here are the three styles side by side, using an OrderService that depends on a PaymentClient.

// ① フィールド
@Service
public class OrderService {
    @Autowired
    private PaymentClient paymentClient;
}

// ② セッター
@Service
public class OrderService {
    private PaymentClient paymentClient;

    @Autowired
    public void setPaymentClient(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }
}

// ③ コンストラクタ
@Service
public class OrderService {
    private final PaymentClient paymentClient;

    @Autowired
    public OrderService(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }
}

As a rule, use option ③, constructor injection. It lets you make fields final and makes it easy to pass in mocks during tests, among other benefits. For the full comparison, see Comparing the Three Dependency Injection Methods.

When You Can Omit @Autowired

Since Spring 4.3, if a class has only one constructor, Spring uses it for injection even without @Autowired. That’s why recent samples rarely show @Autowired.

@Service
public class OrderService {
    private final PaymentClient paymentClient;

    // @Autowired なしでも注入される
    public OrderService(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }
}

Be careful when a class has more than one constructor. If none of them has @Autowired, Spring uses the no-argument constructor.

@Service
public class OrderService {
    private PaymentClient paymentClient;

    public OrderService() {          // こちらが使われる
    }

    public OrderService(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }
    // → paymentClient は null のまま
}

This one is easy to miss: the application starts fine, but you get a NullPointerException at runtime. If you keep several constructors, put @Autowired on the one you want Spring to use.

Only constructors can omit the annotation. Fields and setters are not injected without @Autowired.

Skipping @Autowired with Lombok’s @RequiredArgsConstructor

In real projects you’ll often see this combined with Lombok’s @RequiredArgsConstructor. Lombok generates a single constructor that takes the final fields as arguments, so the omission rule above applies.

@Service
@RequiredArgsConstructor
public class OrderService {
    private final PaymentClient paymentClient;   // 注入される
    private InventoryClient inventoryClient;     // final がないので null のまま
}

A field without final isn’t included in the constructor’s arguments, so it stays null. This is a very common mistake, so watch out for it.

Also, if you put @Qualifier on a field, add the following setting to lombok.config so the annotation is reliably copied to the generated constructor parameter:

lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

For other Lombok annotations, see How to Use Lombok with Spring Boot.

Optional Dependencies: required=false, Optional, and ObjectProvider

For a dependency you want to use only if the Bean exists, there are three options.

@Service
public class ReportService {

    // ① required=false(フィールド・セッター向け)
    @Autowired(required = false)
    private MetricsClient metricsClient;   // Beanがなければ null

    private final Optional<AuditLogger> auditLogger;
    private final ObjectProvider<CacheClient> cacheClient;

    // ② Optional と ③ ObjectProvider はコンストラクタで使える
    public ReportService(Optional<AuditLogger> auditLogger,
                         ObjectProvider<CacheClient> cacheClient) {
        this.auditLogger = auditLogger;
        this.cacheClient = cacheClient;
    }

    public void create() {
        auditLogger.ifPresent(l -> l.log("report created"));

        CacheClient cache = cacheClient.getIfAvailable(); // なければ null
        if (cache != null) {
            cache.evict("report");
        }
    }
}

Here’s how they differ:

ApproachWhen the Bean is missingUse in a constructorWhen there are multiple candidatesWhen the Bean is retrieved
required = falseStays nullNot a good fitExceptionAt startup
Optional<T>Optional.empty()◯ExceptionAt startup
ObjectProvider<T>getIfAvailable() returns null◯getIfUnique() returns nullWhen called

ObjectProvider doesn’t fetch the Bean until you ask for it, so you can also use it to get a fresh prototype-scoped Bean each time. See the Bean scope article for details.

If you’re unsure, take Optional or ObjectProvider as a constructor parameter. With required = false it’s easy to forget a null check, so use it sparingly.

Injecting All Beans of a Type as a List or Map

When there are multiple implementations of the same interface, you can receive all of them at once as a List or a Map.

public interface NotificationSender {
    void send(String message);
}

@Component
@Order(1)
class MailSender implements NotificationSender { /* ... */ }

@Component
@Order(2)
class SlackSender implements NotificationSender { /* ... */ }

@Service
public class NotificationService {
    private final List<NotificationSender> senders;
    private final Map<String, NotificationSender> senderMap;

    public NotificationService(List<NotificationSender> senders,
                               Map<String, NotificationSender> senderMap) {
        this.senders = senders;       // @Order の順(Mail → Slack)
        this.senderMap = senderMap;   // キーはBean名(mailSender, slackSender)
    }

    public void sendAll(String message) {
        senders.forEach(s -> s.send(message));
    }

    public void sendBy(String beanName, String message) {
        senderMap.get(beanName).send(message);
    }
}

The order of the List is set by @Order (or the Ordered interface). In a Map, the keys are Bean names, which works well for the Strategy pattern where you pick an implementation by name. Don’t rely on the order of a Map, though.

The behavior when no matching Beans exist is a little tricky. An @Autowired List on a field or setter throws an exception, but if the class has only one constructor, it receives an empty list. If you want to make it clear that zero Beans is a valid case, orderedStream() on ObjectProvider<NotificationSender> states that intent more clearly.

Checklist: Why Is My @Autowired Value Null?

If you get a null, go through these in order:

  1. You’re creating the instance yourself with new
  2. You put @Autowired on a static field (static fields aren’t injected; the annotation is ignored)
  3. You forgot @Component or @Service on the class
  4. The class is outside the component scan range
  5. You’re using a field-injected value inside the constructor
  6. There are multiple constructors and the no-arg one is being used (see the section on omitting the annotation)
  7. Your test doesn’t start the Spring context

The first one is by far the most common.

// NG: Springが作ったインスタンスではないので、中の @Autowired は動かない
OrderService service = new OrderService();
service.order();   // paymentClient が null

// OK: 使う側もBeanにして、注入してもらう
@RestController
@RequiredArgsConstructor
public class OrderController {
    private final OrderService orderService;
}

The fifth one comes back to the injection order covered earlier. Field injection happens after instantiation, so the field is still null inside the constructor.

@Service
public class PriceService {
    @Autowired
    private TaxCalculator taxCalculator;

    public PriceService() {
        taxCalculator.init();   // NG: まだ注入されていない
    }

    @PostConstruct              // jakarta.annotation.PostConstruct
    void setUp() {
        taxCalculator.init();   // OK: 注入後に呼ばれる
    }
}

Switching to constructor injection avoids this problem entirely.

For the fourth one, check whether the class is in the package of the class annotated with @SpringBootApplication, or in a subpackage of it. How scanning works is explained in What Is @SpringBootApplication?.

For the seventh one, if you use constructor injection, you don’t need @SpringBootTest. You can simply pass in a mock directly.

class OrderServiceTest {
    @Test
    void order() {
        PaymentClient client = Mockito.mock(PaymentClient.class);
        OrderService service = new OrderService(client);  // 自分で渡すのでnullにならない

        service.order();

        Mockito.verify(client).pay(Mockito.any());
    }
}

When @Lazy or lazy initialization is involved, a dependency can also get accessed at an unexpected time. If you suspect that, see the @Lazy article.

Startup Exceptions and What to Check

Sometimes the application doesn’t get as far as a null value and fails at startup instead. When a Bean can’t be found, Spring Boot logs something like this:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.order.OrderService required a bean of type 'com.example.payment.PaymentClient' that could not be found.

Action:

Consider defining a bean of type 'com.example.payment.PaymentClient' in your configuration.

The underlying exception is NoSuchBeanDefinitionException. Check for a missing annotation, check where the package sits, and check whether @ConditionalOnProperty or a profile has disabled the Bean. For more, see How to Fix NoSuchBeanDefinitionException.

When there are too many candidates, you get this instead:

Description:

Parameter 0 of constructor in com.example.order.OrderService required a single bean, but 2 were found:
	- stripePaymentClient: defined in file [.../StripePaymentClient.class]
	- paypalPaymentClient: defined in file [.../PaypalPaymentClient.class]

This is a NoUniqueBeanDefinitionException. Narrow the choice to one Bean with @Primary or @Qualifier, or if you want all of them, take them as a List or Map. For how to narrow them down, see the @Qualifier and @Primary article.

Summary

@Autowired is a marker that asks Spring to find a Bean by type and inject it. The actual work is done by AutowiredAnnotationBeanPostProcessor when the Bean is created.

You can omit it when a class has a single constructor, and combining @RequiredArgsConstructor with final fields is the standard approach today. Use Optional or ObjectProvider for optional dependencies, and a List or Map to receive multiple implementations.

When a value is null, first ask two questions: “Did Spring create this instance?” and “Am I using the value before it’s injected?” Those two usually lead you to the cause.

To learn more about DI, read Comparing the Three Dependency Injection Methods and Choosing Between @Qualifier and @Primary next.