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 <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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值