spring注入bean的3种方式

1.属性注入(DI依赖注入)**

public class SysCollectionExtServiceTest extends AbstractSimpleTest {

    @Autowired
    private SysCollectionExtService sysCollectionExtService;

    @Test
    public void testTuck() {
       
    }
}

优点:简单整洁

缺点:循环依赖注入问题

2.Setter方法注入*

public class SysCollectionExtServiceTest extends AbstractSimpleTest {

    private SysCollectionExtService sysCollectionExtService;
    @Autowired
    public void setSysCollectionExtService(SysCollectionExtService 			      sysCollectionExtService) {
        this.sysCollectionExtService = sysCollectionExtService;
    }

    @Test
    public void testTuck() {
       
    }
}

优点:依赖注入的话,使用的时候会报错

缺点:不简洁,注入太多,显得当前类过于臃肿

提醒:一个类过于太多注入操作,违背了 单一职责原则

3.构造器注入***

public class SysCollectionExtServiceTest extends AbstractSimpleTest {
    
    private SysCollectionExtService sysCollectionExtService;

    @Autowired
    public SysCollectionExtServiceTest(SysCollectionExtService sysCollectionExtService) {
        this.sysCollectionExtService = sysCollectionExtService;
    }

    @Test
    public void testTuck() {
        
    }
}

优点:服务启动,如果存在循环依赖,会报错

缺点:不整洁,注入麻烦

但是4.x以后版本推荐此类注入方式

posted @ 2024-07-23 18:26  土木转行的人才  阅读(60)  评论(0编辑  收藏  举报