栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Autowired的一点延伸

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Autowired的一点延伸

当使用Autowired进行依赖注入的时候,采用的是类型注入。

我们往往采用接口解耦的方式实现,例如定义DataService接口

public interface DataService{

}

然后在使用的时候,使用接口定义成员变量

@Service

public class BusinessServiceImpl inplements BusinessService{

        @Autowired

        private DataService dataService;

这时候就会存在几种情况:

1.  DataService有唯一的实现类,自动注入是成功的。

2.  DataService没有实现类,注入失败。

3.  DataService有多个实现,不知道注入哪个,注入失败。

解决多实现的问题

1. 在某个实现上,使用@Primary注解指定优先注入的实现类型。

interface SortingAlgorithm { 
    
} 
    
@Component 
public class MergeSort implements SortingAlgorithm { 
      // Class code here 
} 
   
@Component 
@Primary 
class QuickSort implements SortingAlgorithm { 
     // Class code here 
}

默认会把QuickSort注入。

2. 使用@Qualifier注解指定具体的实现。(按名称)

@Component 
@Qualifier("mergesort") 
public class MergeSort implements SortingAlgorithm { 
      // Class code here 
} 
    
@Component 
public class QuickSort implements SortingAlgorithm { 
     // Class code here 
} 
    
@Component 
public class SomeService { 

    @Autowired 
    @Qualifier("mergesort") 
    SortingAlgorithm algorithm; 

}

@Qualifier注解表明使用哪个实现来进行注入。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/606365.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号