spring注入方法选择
1.field注入
直接使用注解进行注入,内部使用反射的方式注入到field中 需要注意依赖对象为null报空指针异常,容易出现循环依赖问题
@Autowired
private TestService testService;
2.构造器注入
@Service
public class AService {
private final BService bService;
@Autowired //spring framework 4.3之后可以不用在构造方法上标注@Autowired
public AService(BService bService) {
this.bService = bService;
}
}
3.setter注入
需要使用spring.xml配置,过于臃肿不便使用
@Service
public class BService {
AService aService;
@Autowired
public void setaService(AService aService) {
this.aService = aService;
}
}
循环依赖问题更多的需要在日常的程序设计中避免,比如a依赖b,b依赖a这种需要使用构造器方法避免,但是正常使用属性注入即可