一、困惑

   代码如下,我要用 ILookupService 的方法 ,那我在任何一个要使用的类里都要 @Autowired 一下,如果是个类似工具类的方法到处使用那也太麻烦了



@Autowired
private ILookupService lookupService;

private List<PfLookup> getNameByCode(String code){
Map<String, Object> param = new HashMap<>();
param.put("code", code);
List<PfLookup> lookups = lookupService.listLookupByCode(param);
return lookups;
}


  

二、解决办法

   写一个静态工具类:



@Component
public class ServiceManager {

public static MerchantRepository merchantRepository;


public static ILookupService lookupService;


@Autowired
public void setMerchantRepository(MerchantRepository merchantRepository) {
ServiceManager.merchantRepository = merchantRepository;
}

@Autowired
public void setLookupService(ILookupService lookupService) {
ServiceManager.lookupService = lookupService;
}

}


这样在任何类里都可以直接使用了

ServiceManager.lookupService.方法名


  如下:



public static String getNameByCode(String code){
Map<String, Object> param = new HashMap<>();
param.put("code", code);
List<PfLookup> lookups = ServiceManager.lookupService.listLookupByCode(param);
if(lookups.size() == 0){
logger.error("字典配置有误,code:[{}]", code);
return "字典有误";
}
return lookups.get(0).getName();

}


 


stay hungry stay foolish!