Autowired has two injection methods

  • by type
  • by name

By default, byType is used to inject beans into the Bean. Such as:

@Autowired
private UserService userService;
Copy the code

This code looks for a bean entity injection of type UserService in the Spring container at initialization time, associated with the introduction of UserService.

But if the UserService interface has more than one implementation class, spring will inject an error, for example:

public class UserService1 implements UserService
public class UserService2 implements UserService
Copy the code

At this point, an org. Springframework. Beans. Factory. BeanCreationException, but the reason was that the injection time bean found have 2 matching, but don’t know which one to inject: expected single matching bean but found 2: userService1,userService2

Let’s change it to the following way:

@Autowired
private UserService userService1;

@Autowired
private UserService userService2;

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

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

Running results:

class yjc.demo.serviceImpl.UserService1
class yjc.demo.serviceImpl.UserService2
class yjc.demo.serviceImpl.UserService2
Copy the code

The run result is successful, illustrating two ways to handle multiple implementation classes:

1. The variable name with userService1 userService2, rather than the userService.

Normally @autoWired is injected using the byType method. However, when multiple classes are implemented, the byType method is no longer unique. Instead, it needs to be injected using the byName method, which by default is based on the variable name.

2. Use the @qualifier annotation to indicate which implementation class to use, which is also implemented by byName.

Therefore, the @AutoWired annotation uses byType or byName, but there is a policy, that is, priority. ByType is preferred, followed by byName.