In-depth understanding of Spring AutowireMode: practical exercises + high-quality analysis

AutowireMode is an enumerated type used in Spring to specify the dependency injection method. In the Spring container, we can use annotations such as @Autowired, @Resource or @Inject to automatically inject Bean dependencies, and AutowireMode is used to specify how these annotations work.

AutowireMode has three values:

  • NO (default): Do not autowire. Dependency injection needs to be done manually.
  • BY_NAME: Autowire based on attribute name. Spring will find the matching bean in the container according to the attribute name, and inject it into the current bean. For example, if there is an attribute called "userService" in the current Bean, then Spring will look up whether there is a Bean named "userService" in the container, and inject it into the current Bean.
  • BY_TYPE: Autowire based on attribute type. Spring will find the matching bean in the container according to the attribute type, and inject it into the current bean. For example, if there is an attribute type of UserService in the current Bean, then Spring will find whether there is a Bean of type UserService in the container, and inject it into the current Bean. If there are multiple matching beans in the container, Spring will throw an exception.

Here is an example using BY_NAME autowiring:

@Component
public class UserComponent {
    
    
    @Autowired
    private UserService userService;
}

@Component
public class UserService {
    
    
}

@Configuration
public class AppConfig {
    
    
    @Bean
    public UserComponent userComponent() {
    
    
        return new UserComponent();
    }

    @Bean
    public UserService userService() {
    
    
        return new UserService();
    }
}

In this example, we define a UserComponent and a UserService. A property userService is defined in UserComponent, and we hope that Spring will automatically inject UserService into UserComponent. In order to realize this function, we need to mark @Component annotation on UserComponent, mark @Component on UserService or define UserService Bean in AppConfig. Then use the @Autowired annotation in UserComponent to automatically inject the userService property.

If we use the BY_NAME autowiring method, then Spring will look up the UserService Bean based on the property name and inject it into the UserComponent. Since userService has the same name as the UserService bean, Spring can correctly complete the autowiring.

It should be noted that if there are multiple beans that match the property name or property type, then Spring will throw a NoUniqueBeanDefinitionException. In this case, we need to manually specify the name of the bean to be injected or use the Qualifier annotation to explicitly specify the bean to be injected.

Hope this article can help you understand the use of AutowireMode.

Guess you like

Origin blog.csdn.net/Tanganling/article/details/129883943