Spring中的@Service("dataDictionaryService")注解

Posted vole

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring中的@Service("dataDictionaryService")注解相关的知识,希望对你有一定的参考价值。

1、接口

public interface DataDictionaryService {
    /**
     * 获取兑换率
     * @param coinType 原币种
     * @param billCoin 折币种
     * @param date 取离该时间最近的兑换率
     * @return
     */
    public BigDecimal getExch(String coinType, String billCoin, Date date);

}

技术图片

 

 如图,有两个实现类。

2、实现类

@Service("dataDictionaryService")
public class DataDictionaryCache implements DataDictionaryService{
    @Autowired
    private DataDictionaryServiceImpl dataDictionaryService;

    private Map<ExchConditions,Exch> exchMap = new ConcurrentHashMap<>();

    @Autowired
    private CacheManager cacheManager;

    //private Map<PrpDcurrency,prpDcurrency> prpDcurrencyMap=new ConcurrentHashMap<>();

    @Override
    public BigDecimal getExch(String coinType, String billCoin, Date date) {
        ExchConditions exchConditions = new ExchConditions(coinType,billCoin,date);
        if(!exchMap.containsKey(exchConditions)
                || exchMap.get(exchConditions).isTimeout()){
            BigDecimal exch = dataDictionaryService.getExch(coinType,billCoin,date);
            exchMap.put(exchConditions,new Exch(exch));
        }
        return exchMap.get(exchConditions).getExchrate();
    }
}


@Component
public class DataDictionaryServiceImpl implements DataDictionaryService {

@Autowired
private DictAPIService dictService;

@Autowired
private RelationBreakMapper relationBreakMapper;

@Autowired
private OutstandingBreakMapper outstandingBreakMapper;
@Autowired
private AssessBreakMapper assessBreakMapper;

/**
* 获取兑换率
* @param coinType 原币种
* @param billCoin 折币种
* @param date 取离该时间最近的兑换率
* @return
*/
@Override
public BigDecimal getExch(String coinType, String billCoin, Date date) {
PrpDexch exch = null;
try {
exch = dictService.getPrpDexch("dms", date, coinType, billCoin);
} catch (Exception e) {

return BigDecimal.ZERO;
}
return exch == null ? BigDecimal.ZERO : exch.getExchRate().divide(new BigDecimal(exch.getBase()));
}

3、调用

@Controller
@RequestMapping(value ="/dataDict")
public class DataDictController {

    @Autowired
    private DataDictionaryService dataDictionaryService;

说明:当一个接口有两个实现类时,需要在一个实现类的注解后加上@Service("dataDictionaryService")引号中的说明,在Controller调用时,属性名称必须与引号中的名称一致,不然无法识别创建哪个实现类的Bean。

其实会出现编译报错如下:

技术图片

 

 

不能自动装配。“DataDictionaryService”类型的bean不止一个。

bean:

dataDictionaryCache (dataDictionaryCache .java)

dataDictionaryServiceImpl (dataDictionaryServiceImpl .java)

以上是关于Spring中的@Service("dataDictionaryService")注解的主要内容,如果未能解决你的问题,请参考以下文章

spring注解@service括号中的service有啥用

独立的main方法调用Spring MVC框架中的service

Spring的注解@Service ("a")与@Service (value ="b")各表示什

spring 中的事物管理问题

spring bean中的properties元素内的ref和value的区别;* 和 ** 的区别

恳请spring配置文件逐条详解,详见问题补充。