SpringBoot启动加载自己的策略类到容器中使用?

使用InitializingBean接口

springboot中在启动的会自动把所有的实现同一个接口的类,都会转配到标注@Autowired的list里面
而且实现了InitializingBean接口,在启动的赋值的时候,我们会把所有的策略类,重放到map中,我们在使用的时候,更具唯一code,找到对应的实现类即可。

public class xxxxx implements InitializingBean {


    @Autowired
    private List<策略类的接口> xxxxLists;

    private Map<每一个策略的唯一code,策略类的接口> xxxxMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        xxxxMap = xxxxLists.stream().collect(Collectors.toMap(策略类唯一code,Function.identity()));
    }
}

实现ApplicationContextAware类

通过后置处理器,把容器相同的类找到,然后加载到map中使用

public class xxxxxx implements ApplicationContextAware {

    private Map<每一个策略的唯一code,策略类的接口> xxxxMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, CityInfoServiceController> beansOfType = applicationContext.getBeansOfType(xxxxxx.class);
        beansOfType.forEach((key,value)->{
            xxxxMap.put(value.getCode(),value);
        });
    }
}

每一个策略接口

public interface MyHandle {
    
    //每一个策略都有一个唯一一个code(建议使用枚举列出,方便使用)
    public String getHandleCode();
    
    //实现具体策略实现(可以返回具体数据,也可以返回void)
    public void handleMethod(Object data);
    
}

相关推荐

  1. SpringBoot启动自己策略容器使用

    2024-04-15 09:06:04       113 阅读
  2. springboot启动数据库数据内存

    2024-04-15 09:06:04       62 阅读
  3. springboot启动热点数据Redis

    2024-04-15 09:06:04       53 阅读
  4. Spring容器Bean和JVM

    2024-04-15 09:06:04       23 阅读
  5. 深度分析thinkphp自动

    2024-04-15 09:06:04       38 阅读
  6. springboot,配置过程

    2024-04-15 09:06:04       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-15 09:06:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-15 09:06:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-15 09:06:04       82 阅读
  4. Python语言-面向对象

    2024-04-15 09:06:04       91 阅读

热门阅读

  1. Python和R概率统计算法建模评估气象和运动

    2024-04-15 09:06:04       89 阅读
  2. Qt实现Kermit协议(六)

    2024-04-15 09:06:04       42 阅读
  3. IDE:常见的集成开发环境

    2024-04-15 09:06:04       200 阅读
  4. C语言数组的初始化方法大全

    2024-04-15 09:06:04       34 阅读
  5. 软件测试Linux 必备考点

    2024-04-15 09:06:04       134 阅读