本文主要是介绍Guide to Spring @Autowired 走近Spring的@Autowired注解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文链接: Guide to Spring @Autowired
1. Overview 概述
Starting with Spring 2.5, the framework introduced annotations-driven Dependency Injection. The main annotation of this feature is @Autowired. It allows Spring to resolve and inject collaborating beans into our bean.
从Spring的2.5版本开始,引入了基于注解的依赖注入。这个新功能的主要注解就是@Autowired注解,它允许Spring框架解析它所标记的依赖,并把它注入到我们的bean对象中。
In this tutorial, we'll first take a look at how to enable autowiring and the various ways to autowire beans. Afterward, we'll talk about resolving bean conflicts using @Qualifier annotation, as well as potential exception scenarios.
这篇文章中,首先看一下如何启用自动注入,并查看有几种方式来注入依赖bean。稍后,将介绍如何使用@Qualifier注解来解决bean对象冲突,还有一些可能出现异常的场景。
2. Enabling @Autowired Annotations 启用@Autowired注解功能
The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.
Spring框架默认启动了自动依赖注入,换句话说,通过在配置文件中声明bean的依赖,Spring容器会自动关联声明了引用关系的bean对象,进行依赖注入,这就是Spring的自动注入。
To use Java-based configuration in our application, let's enable annotation-driven injection to load our Spring configuration:
要使用Java类进行配置,那么要启用基于注解的注入功能来加载Spring配置,示例如下:
@Configuration
@ComponentScan("com.baeldung.autowire.sample")
public class AppConfig {}
Alternatively, the annotation"><context:annotation-config> annotation is mainly used to activate the dependency injection annotations in Spring XML files.
或者,在XML文件中可以使用<context:annotion-config>来标记启用注解注入功能,这个标签也是最常用的启动这一功能的标签。
Moreover, Spring Boot introduces the @SpringBootApplication annotation. This single annotation is equivalent to using @Configuration,
这篇关于Guide to Spring @Autowired 走近Spring的@Autowired注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!