【Spring】字段注入@AutoWired、构造器注入、setter注入

Spring官网推荐使用构造器注入和setter注入:https://docs.spring.io/spring-framework/docs/5.2.12.RELEASE/spring-framework-reference/core.html#spring-core

1.通过@Autowired注入对象,又叫字段注入

Spring官方不推荐这种写法,原因有:单一职责,无法注入final字段,测试时类无法被单独实例化、需要提供类所需的依赖等。

不用担心循环依赖,@Autowired内部解决了这个问题。

2.constructor注入。

对于强依赖,建议使用这种方式。

有循环依赖的风险,官方建议在可能存在循环依赖的类中使用setter注入代替constructor注入。

3.setter注入。官网推荐

可以赋空值。对于非必需的依赖,建议使用这种方式。


Demo

Controller

@RestController
public class PersonController {

    private final PersonService personService;

    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @GetMapping("/test")
    public void test() {
        personService.sleep();
        personService.whisper();
    }
}

Service

@Service
public class PersonService {
    private final AnimalService animalService;

    private FlowerService flowerService;

    public PersonService(AnimalService animalService) {
        this.animalService = animalService;
    }

    @Autowired
    public void setFlowerService(FlowerService flowerService) {
        this.flowerService = flowerService;
    }

    public void sleep() {
        animalService.sleep();
    }

    public void whisper(){
        flowerService.whisper();
    }
}
@Service
public class FlowerService {
    public void whisper() {
        System.out.println("l'm beautiful flower.");
    }
}
@Service
public class AnimalService {
    public void sleep() {
        System.out.println("l'm sleeping..zzz");
    }
}

控制台输出

l'm sleeping..zzz
l'm beautiful flower.


参考:这些文章我没看完,只是为了记录,方便以后查看

构造器注入引起循环依赖的解决方法 https://blog.csdn.net/programmer_at/article/details/82389221

@AutoWired源码-Spring如何解决循环依赖 https://blog.csdn.net/scientificCommunity/article/details/109220092


https://blog.csdn.net/qq1309664161/article/details/119293360

@Autowired在构造方法上:

当一个类中有多个构造方法,且要选择某一个构造方法进行实例化类时,可以在构造方法上加@Autowired注解。

@Autowired在普通方法上:

当Spring容器调用该类的构造方法实例化类后,会调用@Autowired修饰的其他方法。

@Autowired在类属性上:

实例化类后,属性被注入。

posted @ 2023-02-10 14:52  musecho  阅读(771)  评论(0)    收藏  举报