第一,简单方法。SpringContext.getBean的方式获取bean

public class RuleConfigParser {

	 private ConfigBean configBean;
	
	 private void initBeans()
    {
        if(diamondConfigBean==null)
        {
	configBean = SpringContext.getBean(ConfigBean.class);
	}
	}
	}

第二,工厂模式获取。ApplicationContextAware接口

public class RuleConfigParserFactory implements ApplicationContextAware {
  private static final Map<String, RuleConfigParser> cachedParsers = new HashMap<>();

  @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, RuleConfigParser> clientMap = applicationContext.getBeansOfType(RuleConfigParser.class);
        if(clientMap != null){
            for (RuleConfigParser parser : clientMap.values()) {
                if(adapter.getSourceType() != null){
                    cachedParsers.put(adapter.getSourceType(), adapter);
                }
            }
        }
    }

  public static IRuleConfigParser getParser(String configFormat) {
    if (configFormat == null || configFormat.isEmpty()) {
      return null;//返回null还是IllegalArgumentException全凭你自己说了算
    }
    IRuleConfigParser parser = cachedParsers.get(configFormat.toLowerCase());
    return parser;
  }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐