Talking about two injection modes of SpringBoot @ Autowired

  • 2021-10-15 10:47:33
  • OfStack

Autowired has two injection modes

by type by name

By default, byType is used to inject the corresponding Bean into Bean. For example:


@Autowired
private UserService userService;

This code will look for an bean entity injection of type UserService in the spring container at initialization time, associated with the introduction of userService.
However, if there are multiple implementation classes of UserService interface, an error will be reported when spring is injected, for example:


public class UserService1 implements UserService
public class UserService2 implements UserService

Error org. springframework. beans. factory. BeanCreationException will be reported at this time, and the reason is that two matching bean are found during injection, but it is not known which one to inject: expected single matching bean but found 2: userService1, userService2
We changed it to the following way:


@Autowired
private UserService userService1;

@Autowired
private UserService userService2;

@Autowired
@Qualifier(value = "userService2")
private UserService userService3;

@Test
public void test(){
    System.out.println(userService1.getClass().toString());
    System.out.println(userService2.getClass().toString());
    System.out.println(userService3.getClass().toString());
}

Run results:

class yjc.demo.serviceImpl.UserService1
class yjc.demo.serviceImpl.UserService2
class yjc.demo.serviceImpl.UserService2

The running result was successful, which explained two methods to deal with multiple implementation classes:

1. Use userService1, userService2 instead of userService for variable names.
Usually @ Autowired is injected by byType, but when multiple classes are implemented, byType is no longer the only one, but needs to be injected by byName, and this name is based on variable names by default.

2. Use the @ Qualifier annotation to indicate which implementation class to use, which is actually implemented through byName.
From this point of view, whether the @ Autowired annotation uses byType or byName actually has a certain strategy, that is, it has priority. byType is preferred, followed by byName.


Related articles: