Skip to content

Commit 9db4b43

Browse files
committed
[docs unpdate]Spring 注入一个 bean 常用的注解
1 parent f6c097b commit 9db4b43

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

docs/system-design/framework/spring/spring-knowledge-and-questions-summary.md

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,18 @@ public OneService getService(status) {
208208
}
209209
```
210210

211+
### 注入 Bean 的注解有哪些?
212+
213+
Spring 内置的 `@Autowired` 以及 JDK 内置的 `@Resource``@Inject` 都可以用于注入 Bean。
214+
215+
| Annotaion | Package | Source |
216+
| ------------ | ---------------------------------- | ------------ |
217+
| `@Autowired` | `org.springframework.bean.factory` | Spring 2.5+ |
218+
| `@Resource` | `javax.annotation` | Java JSR-250 |
219+
| `@Inject` | `javax.inject` | Java JSR-330 |
220+
221+
`@Autowired``@Resource`使用的比较多一些。
222+
211223
### @Autowired@Resource 的区别是什么?
212224

213225
`Autowired` 属于 Spring 内置的注解,默认的注入方式为`byType`(根据类型进行匹配),也就是说会优先根据接口类型去匹配并注入 Bean (接口的实现类)。
@@ -240,7 +252,7 @@ private SmsService smsService;
240252

241253
我们还是建议通过 `@Qualifier` 注解来显示指定名称而不是依赖变量的名称。
242254

243-
`@Resource`属于 JDK 提供的注解,默认注入方式为 `byName`如果无法通过名称匹配到对应的实现类的话,注入方式会变为`byType`
255+
`@Resource`属于 JDK 提供的注解,默认注入方式为 `byName`如果无法通过名称匹配到对应的 Bean 的话,注入方式会变为`byType`
244256

245257
`@Resource` 有两个比较重要且日常开发常用的属性:`name`(名称)、`type`(类型)。
246258

@@ -258,10 +270,9 @@ public @interface Resource {
258270
@Resource
259271
private SmsService smsService;
260272
// 正确注入 SmsServiceImpl1 对象对应的 bean
261-
@Autowired
273+
@Resource
262274
private SmsService smsServiceImpl1;
263275
// 正确注入 SmsServiceImpl1 对象对应的 bean(比较推荐这种方式)
264-
@Autowired
265276
@Resource(name = "smsServiceImpl1")
266277
private SmsService smsService;
267278
```
@@ -270,7 +281,7 @@ private SmsService smsService;
270281

271282
- `@Autowired` 是 Spring 提供的注解,`@Resource` 是 JDK 提供的注解。
272283
- `Autowired` 默认的注入方式为`byType`(根据类型进行匹配),`@Resource`默认注入方式为 `byName`(根据名称进行匹配)。
273-
- 当一个类存在多个实现类的情况下`@Autowired``@Resource`都需要通过名称进行匹配才能正确匹配到对应的 Bean。`Autowired` 可以通过 `@Qualifier` 注解来显示指定名称,`@Resource`可以通过 `name` 属性来显示指定名称。
284+
- 当一个接口存在多个实现类的情况下`@Autowired``@Resource`都需要通过名称才能正确匹配到对应的 Bean。`Autowired` 可以通过 `@Qualifier` 注解来显示指定名称,`@Resource`可以通过 `name` 属性来显示指定名称。
274285

275286
### Bean 的作用域有哪些?
276287

0 commit comments

Comments
 (0)