其实这是因为 @Autowired 是 Spring 提供的特定注解,和 Spring 框架绑定,而 @Resource 是JSR-250提供的,它是Java标准,作为 IOC 容器框架都是需要实现的,所以不存在上面的第一点问题。
一些最佳实践
Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a required dependency.
public class TestService {
/**
* 必须依赖
*/
private final DependencyA dependencyA;
/**
* 非必须依赖
*/
private DependencyB dependencyB;
public TestService(DependencyA dependencyA) {
this.dependencyA = dependencyA;
}
@Autowired(required = false)
public void setDependencyB(DependencyB dependencyB) {
this.dependencyB = dependencyB;
}
使用构造器注入带来的循环依赖问题
如果我们使用构造器注入,那么可能会出现无法解析循环依赖的问题。这里提供两个解决方案:
使用方法注入(官网推荐)
One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In other words, although it is not recommended, you can configure circular dependencies with setter injection.
使用 Lazy 注解(推荐但谨慎使用)
一些场景下会导致初次请求处理变慢。
Java复制代码
@Service
public class DependencyA {
private final TestService testService;
public DependencyA(@Lazy TestService testService) {
this.testService = testService;
}
}
@Service
public class TestService {
private final DependencyA dependencyA;
public TestService(DependencyA dependencyA) {
this.dependencyA = dependencyA;
}
}