几种spring注册service方式

216 阅读1分钟
@Slf4j
@Component
public class ListFactory implements ApplicationContextAware {

    public Map<String, IList> listContainer = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(CustomerListType.class);
        beansWithAnnotation.forEach((customerListType, beans) -> {
            Class<IList> beansClass = (Class<IList>) beans.getClass();
            String type = beansClass.getAnnotation(CustomerListType.class).value().getCode();
            listContainer.put(type, applicationContext.getBean(beansClass));
        });
    }

    public IList getInstance(String type) throws IllegalArgumentException {
        Preconditions.checkArgument(CustomerConstant.ListType.getAllTypes().contains(type), "列表类型错误");
        return listContainer.get(type);
    }
}
@Component
public class ListContent {

    @Autowired
    public Map<String, IList> listContainer;

    public IList getInstance(String type) throws IllegalArgumentException {
        Preconditions.checkArgument(CustomerConstant.ListType.getAllTypes().contains(type), "列表类型错误");
        return listContainer.get(type);
    }
}