Spring框架中@Inject和@Autowired的区别及使用场景

Spring框架中@Inject和@Autowired的区别及使用场景

技术背景

在Spring框架中,依赖注入(Dependency Injection,DI)是一个核心特性,它允许对象之间的依赖关系在运行时被动态地注入,而不是在对象内部硬编码。@Inject@Autowired 都是用于实现依赖注入的注解,但它们来源和特性有所不同。@Inject 是Java CDI(Contexts and Dependency Injection)标准(JSR - 330)的一部分,而 @Autowired 是Spring框架自己定义的注解。

实现步骤

1. 使用 @Autowired

1
2
3
4
5
6
7
8
9
10
11
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerService {

@Autowired
private CustomerOrderService customerOrderService;

// 其他方法
}

2. 使用 @Inject

1
2
3
4
5
6
7
8
9
10
11
import javax.inject.Inject;
import org.springframework.stereotype.Service;

@Service
public class CustomerService {

@Inject
private CustomerOrderService customerOrderService;

// 其他方法
}

核心代码

以下是一个简单的示例,展示了如何在Spring应用中使用这两个注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// 服务接口
interface CustomerOrderService {
void processOrder();
}

// 服务实现类
@Component
class DefaultCustomerOrderService implements CustomerOrderService {
@Override
public void processOrder() {
System.out.println("Processing order...");
}
}

// 使用 @Autowired 的类
@Component
class AutowiredCustomerService {
@Autowired
private CustomerOrderService customerOrderService;

public void doSomething() {
customerOrderService.processOrder();
}
}

// 使用 @Inject 的类
@Component
class InjectCustomerService {
@Inject
private CustomerOrderService customerOrderService;

public void doSomething() {
customerOrderService.processOrder();
}
}

最佳实践

使用 @Autowired

  • 当你明确使用Spring框架进行开发,并且需要利用Spring的特定功能时,建议使用 @Autowired。例如,需要使用 required 属性来控制依赖注入的必要性。
  • 在Spring Boot项目中,@Autowired 是更常用的选择,因为它与Spring的生态系统紧密集成。

使用 @Inject

  • 当你希望代码具有更好的可移植性,不依赖于特定的框架时,可以使用 @Inject。例如,你可能有计划在未来将项目迁移到其他支持JSR - 330的依赖注入框架中。
  • 在编写可复用的组件或库时,使用 @Inject 可以减少对Spring框架的依赖。

常见问题

1. @Autowired@Inject 的行为是否完全相同?

在大多数情况下,它们的行为是相同的。Spring从3.0版本开始支持 @Inject 注解,并且将其与 @Autowired 视为同义词。但 @Autowired 有一个 required 属性,而 @Inject 没有。

2. 当依赖不存在时,两者的处理方式有何不同?

  • @Autowiredrequired 属性默认为 true,如果找不到匹配的依赖,会抛出异常。可以将 required 属性设置为 false 来避免这种情况。
  • @Inject 没有 required 属性,如果找不到匹配的依赖,会抛出异常。

3. 如何选择使用哪个注解?

如果你的项目只使用Spring框架,并且需要利用Spring的特定功能,建议使用 @Autowired。如果你的项目需要更好的可移植性,或者希望遵循Java标准,建议使用 @Inject


Spring框架中@Inject和@Autowired的区别及使用场景
https://119291.xyz/posts/2025-04-21.difference-between-inject-and-autowired-in-spring/
作者
ww
发布于
2025年4月22日
许可协议