If you put @Autowired on a field in IntelliJ IDEA, you get the warning “Field injection is not recommended.” Many developers learn field injection in onboarding training, then get told in code review to “switch this to constructor injection.” Let’s look at why the three injection styles are treated differently.

By the end of this article, you’ll be able to explain how the three styles differ in four areas: testability, null safety, immutability, and circular dependency detection. You’ll also know which one to use when you write new code. If dependency injection itself still feels unclear, start with What Is DI?.

The Three Styles

Spring Boot gives you three ways to receive dependent Beans. Constructor injection passes them in as constructor arguments. Setter injection passes them through setter methods. Field injection puts @Autowired directly on a field.

Since Spring 4.3, you can leave out @Autowired when a class has only one constructor, and injection still works. That’s why you rarely see @Autowired in modern Spring Boot code.

What Is Constructor Injection?

With constructor injection, a class receives the Beans it depends on as constructor arguments. When Spring creates the Bean, it calls the constructor and passes in Beans that match the argument types. This is the style currently recommended for Spring Boot.

If there’s only one constructor, you don’t need @Autowired. If there are several, Spring can’t tell which one to use, so put @Autowired on the one you want it to use for injection.

@Service
public class ReportService {
    private final UserRepository userRepository;
    private final Clock clock; // Clock は別途 @Bean で定義している前提

    @Autowired
    public ReportService(UserRepository userRepository, Clock clock) {
        this.userRepository = userRepository;
        this.clock = clock;
    }

    // テスト用などの補助コンストラクタ
    public ReportService(UserRepository userRepository) {
        this(userRepository, Clock.systemDefaultZone());
    }
}

Note that “constructor binding” in @ConfigurationProperties is a different feature. It binds configuration values to a class and has nothing to do with the Bean injection covered here.

The Same Service Written Three Ways

Our example is a UserService that depends on a UserRepository. First, field injection:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User find(Long id) {
        return userRepository.findById(id).orElseThrow();
    }
}

Next, setter injection:

@Service
public class UserService {
    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User find(Long id) {
        return userRepository.findById(id).orElseThrow();
    }
}

And finally, constructor injection, with @Autowired left out:

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User find(Long id) {
        return userRepository.findById(id).orElseThrow();
    }
}

At first glance, field injection looks best because it’s the shortest. What really matters, though, is what each style guarantees.

Testability

Testability is the main reason constructor injection is recommended. In a unit test, you can pass in a mock just by calling new.

@Test
void findユーザー() {
    UserRepository repo = mock(UserRepository.class);
    when(repo.findById(1L)).thenReturn(Optional.of(new User(1L, "taro")));

    UserService service = new UserService(repo);

    assertThat(service.find(1L).getName()).isEqualTo("taro");
}

With field injection, the mock has to go straight into a private field. Your only options are reflection or starting the context with @SpringBootTest. Either way, tests get heavier, and you can no longer write plain POJO tests that don’t depend on Spring.

With setter injection, you can call setUserRepository(...). However, as you add dependencies, it’s easy to forget one of those calls and hit an NPE.

Null Safety and Immutability

Constructor injection lets you declare fields final. A final field must be set by the time the constructor finishes, so once a UserService instance exists, none of its dependencies can be null.

With field or setter injection, the language still allows a method to be called before Spring sets the value. Anyone reading the code can’t easily tell when the dependencies are actually available.

If a required Bean is missing, a required @Autowired fails at startup with UnsatisfiedDependencyException, whichever style you use. The difference shows up when you create an instance outside Spring. In a test, calling new UserService() on a field-injected class gives you an object whose dependencies are null, and you only get an NPE once you call a method. With constructor injection, the code won’t compile unless you pass the arguments.

When Do Circular Dependencies Surface?

Say AService needs BService and BService needs AService. Since Spring Boot 2.6, spring.main.allow-circular-references defaults to false, so the application fails at startup no matter which injection style you use.

The dependencies of some of the beans in the application context form a cycle:
┌─────┐
|  aService defined in file [.../AService.class]
↑     ↓
|  bService defined in file [.../BService.class]
└─────┘

The styles only behave differently when you set this property to true to allow cycles. With field or setter injection, Spring can create one Bean first and inject it into the other afterward, so the application starts even though the cycle is still there. The problem may then show up at runtime, for example as an infinite loop, which is much harder to track down. Constructor injection needs the other Bean’s instance just to create the object, so even with cycles allowed, startup fails with BeanCurrentlyInCreationException.

The sooner you find a design problem, the better. Spring Boot 2.6 banned circular dependencies by default for the same reason: if you have a cycle, rethink your design. Use the setting that allows cycles only as a stopgap during a migration.

Less Boilerplate with Lombok’s @RequiredArgsConstructor

The one downside of constructor injection is boilerplate, and Lombok’s @RequiredArgsConstructor removes it.

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final NotificationService notificationService;

    public User find(Long id) {
        return userRepository.findById(id).orElseThrow();
    }
}

Lombok generates a constructor that takes only the final fields as arguments. Adding a dependency then takes a single private final ... line, which keeps changes as small as possible. To set Lombok up, see How to Use Lombok.

Why IntelliJ Shows This Warning

The “Field injection is not recommended” warning has three reasons behind it. First, field injection makes testing harder. Second, you can’t use final, so you can’t keep the object immutable. Third, dependencies don’t appear in the constructor signature, so they stay hidden.

Converting existing code is mechanical. Remove @Autowired from each field, add final, and put @RequiredArgsConstructor on the class. That’s all it takes to clear the warning.

What Is Setter Injection? When It Makes Sense

With setter injection, a class receives its dependencies through setter methods annotated with @Autowired. Spring creates the instance first and then calls the setters to inject the dependencies. Dependencies can be swapped later, but fields can’t be final, and they stay null until the setter is called. That makes setter injection a poor fit for required dependencies.

Constructor injection isn’t the answer for everything, though. Setters do have their uses, and optional dependencies are the most common one.

@Autowired(required = false)
public void setMetricsClient(MetricsClient client) {
    this.metricsClient = client;
}

If there’s no MetricsClient Bean, Spring never calls the setter, and the application still starts normally. That said, you can also handle optional dependencies with constructor injection by using ObjectProvider. It lets you say “use this if it’s available” while keeping the field final, so consider it for new code too.

@Service
public class OrderService {
    private final ObjectProvider<MetricsClient> metricsClient;

    public OrderService(ObjectProvider<MetricsClient> metricsClient) {
        this.metricsClient = metricsClient;
    }

    public void place(Order order) {
        // MetricsClient は自前で定義した計測用インターフェースの例
        metricsClient.ifAvailable(client -> client.count("order.placed"));
    }
}

The other case is a last resort: existing code where you can’t remove a cycle and have set spring.main.allow-circular-references=true. As the next section explains, the real fix is to change the design.

Solve Circular Dependencies Through Design

Adding @Lazy makes a circular dependency appear to work.

public AService(@Lazy BService bService) {
    this.bService = bService;
}

But this is only a band-aid. A cycle is really a sign that responsibilities should be split. A common refactoring is to move the logic both classes need into a third Bean. Another option is to replace the two-way calls with events sent through ApplicationEventPublisher, so the compile-time dependency only goes one way.

To get a clearer picture of how to split component responsibilities, also read What Is @Component? and Bean Scopes Explained.

Summary

For new code, default to constructor injection + @RequiredArgsConstructor. Tests are easier to write, your objects are immutable and never hold null dependencies, and circular dependencies are caught at startup.

A practical rule: use setter injection only for optional dependencies, and keep field injection for test classes and throwaway, script-like code. Treat IntelliJ’s warning as a reminder to clean up your design, and when you see it, just fix it.