美文网首页
Spring Bean 注入示例

Spring Bean 注入示例

作者: Tinyspot | 来源:发表于2022-10-19 21:55 被阅读0次

    1. 接口多实现

    @RestController
    public class ProviderController {
        @Resource
        private Provider queryProvider;
        @Resource
        private Provider subQueryProvider;
    
        @RequestMapping("/provider")
        public String provider() {
            queryProvider.execute();
            subQueryProvider.execute();
            return "provider";
        }
    }
    

    接口

    public interface Provider {
        void execute();
    }
    
    public interface SubProvider extends Provider {
    }
    

    实现类

    @Service
    public class QueryProvider implements Provider {
        @Override
        public void execute() {
            System.out.println("QueryProvider...");
        }
    }
    
    @Service
    public class SubQueryProvider implements SubProvider {
        @Override
        public void execute() {
            System.out.println("SubQueryProvider...");
        }
    }
    

    2. 接口调用链

    2.1 常用写法

    @RestController
    public class CommonProcessorController {
    
        @Resource
        private CommonProcessor commonProcessor;
        @Resource
        private CommonProcessor batchCommonProcessor;
    
        @RequestMapping("/config/common")
        public String commonConfig() {
            BaseContext context = new QueryContext();
            commonProcessor.execute(context);
            return "common processor";
        }
    
        @RequestMapping("/config/batch")
        public String batchConfig() {
            BaseContext context = new QueryContext();
            batchCommonProcessor.execute(context);
            return "batch common processor";
        }
    }
    

    注入 Bean

    @Configuration
    public class CommonProcessorConfig {
    
        @Resource
        private IProcessor queryProcessor;
        @Resource
        private IProcessor updateProcessor;
        @Resource
        private IProcessor batchProcessor;
    
        @Bean
        public CommonProcessor commonProcessor() {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = new ArrayList<>();
            processorList.add(queryProcessor);
            processorList.add(updateProcessor);
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    
        @Bean
        public CommonProcessor batchCommonProcessor() {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = Arrays.asList(batchProcessor);
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    }
    
    public class CommonProcessor {
        
        private List<IProcessor> processorList;
        
        public void execute(BaseContext context) {
            for (IProcessor processor : processorList) {
                processor.execute(context);
            }
        }
    
        public List<IProcessor> getProcessorList() {
            return processorList;
        }
    
        public void setProcessorList(List<IProcessor> processorList) {
            this.processorList = processorList;
        }
    }
    
    public interface IProcessor<T extends BaseContext> {
        void execute(T context) throws RuntimeException;
    }
    
    @Component
    public class QueryProcessor implements IProcessor<QueryContext> {
        @Override
        public void execute(QueryContext context) throws RuntimeException {
            context.setTotal(100);
            System.out.println("QueryProcessor: " + JSON.toJSONString(context));
        }
    }
    
    @Component
    public class UpdateProcessor implements IProcessor<QueryContext> {
        @Override
        public void execute(QueryContext context) throws RuntimeException {
            context.setName("update");
            System.out.println("UpdateProcessor: " + JSON.toJSONString(context));
        }
    }
    
    @Component
    public class BatchProcessor implements IProcessor<QueryContext> {
        
        @Override
        public void execute(QueryContext context) throws RuntimeException {
            context.setName("batch");
            context.setTotal(200);
            System.out.println("BatchProcessor..." + JSON.toJSONString(context));
        }
    }
    
    @Data
    public class QueryContext extends BaseContext {
        private static final long serialVersionUID = -3626780096892721560L;
    
        private Integer total;
        
        private String name;
    
        public QueryContext() {}
    
        public QueryContext(BaseContext baseContext) {
            super(baseContext);
        }
    }
    
    public class BaseContext implements Serializable {
        private static final long serialVersionUID = -1013819823166401300L;
    
        private Request request;
        private Response response;
        private BaseContext baseContext;
    
        public BaseContext() {
    
        }
    
        public BaseContext(BaseContext baseContext) {
            this.baseContext = baseContext;
        }
    
        public Request getRequest() {
            if (baseContext != null) {
                return baseContext.getRequest();
            }
            return request;
        }
    
        public void setRequest(Request request) {
            if (baseContext != null) {
                baseContext.setRequest(request);
            }
            this.request = request;
        }
    
        public Response getResponse() {
            if (baseContext != null) {
                return baseContext.getResponse();
            }
            return response;
        }
    
        public void setResponse(Response response) {
            if (baseContext != null) {
                baseContext.setResponse(response);
            }
            this.response = response;
        }
    
        @Data
        public static class Request {
            private String baseName;
        }
    
        @Data
        public static class Response {
    
        }
    }
    

    2.2 在方法参数注入

    @Configuration
    public class CommonProcessorConfig {
    
        @Bean
        public CommonProcessor commonProcessor(IProcessor queryProcessor, IProcessor updateProcessor) {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = new ArrayList<>();
            processorList.add(queryProcessor);
            processorList.add(updateProcessor);
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    
        @Bean
        public CommonProcessor batchCommonProcessor(IProcessor batchProcessor) {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = Arrays.asList(batchProcessor);
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    }
    

    2.3 @Bean 方式注入

    @Configuration
    public class CommonProcessorConfigBack2 {
    
        @Bean
        public CommonProcessor commonProcessor() {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = new ArrayList<>();
            processorList.add(queryProcessor());
            processorList.add(updateProcessor());
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    
        @Bean
        public CommonProcessor batchCommonProcessor() {
            CommonProcessor commonProcessor = new CommonProcessor();
            List<IProcessor> processorList = Arrays.asList(batchProcessor());
            commonProcessor.setProcessorList(processorList);
            return commonProcessor;
        }
    
        @Bean
        public IProcessor queryProcessor() {
            return new QueryProcessor();
        }
    
        @Bean
        public IProcessor updateProcessor() {
            return new UpdateProcessor();
        }
    
        @Bean
        public IProcessor batchProcessor() {
            return new BatchProcessor();
        }
    }
    

    注意:此方式注入 bean, 需要将 QueryProcessor, 的 @Component 注解去掉

    3. 升级

    @RestController
    public class CommonProcessorController {
        @Resource
        private ProcessorEnumBuild processorEnumBuild;
    
        @RequestMapping("/config/enum")
        public String enumConfig() {
            CommonProcessor processor = processorEnumBuild.getProcessorByBizType("COMMON_BIZ_PROCESSOR");
            processor.execute(new QueryContext());
            return JSON.toJSONString(processorEnumBuild.getProcessorMap());
        }
    }
    
    @Component
    public class ProcessorEnumBuild implements ApplicationContextAware, InitializingBean {
    
        public static ApplicationContext applicationContext;
    
        private Map<String, CommonProcessor> processorMap = new HashMap<>();
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            ProcessorEnumBuild.applicationContext = applicationContext;
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            for (ProcessTypeEnum value : ProcessTypeEnum.values()) {
                CommonProcessor processor = (CommonProcessor) applicationContext.getBean(value.getProcessName());
                processorMap.put(value.getBizType(), processor);
            }
        }
    
        public CommonProcessor getProcessorByBizType(String processorName) {
            return processorMap.get(processorName);
        }
    
        public Map<String, CommonProcessor> getProcessorMap() {
            return processorMap;
        }
    }
    
    public enum ProcessTypeEnum {
    
        COMMON_BIZ_PROCESSOR("COMMON_BIZ_PROCESSOR", "commonProcessor", "普通执行器"),
        BATCH_BIZ_PROCESSOR("BATCH_BIZ_PROCESSOR", "batchCommonProcessor", "批量执行器"),
        ;
    
        private String bizType;
        private String processName;
        private String desc;
    
        ProcessTypeEnum(String bizType, String processName, String desc) {
            this.bizType = bizType;
            this.processName = processName;
            this.desc = desc;
        }
    
        public String getBizType() {
            return bizType;
        }
    
        public String getProcessName() {
            return processName;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public ProcessTypeEnum getProcessor(String bizType) {
            for (ProcessTypeEnum value : values()) {
                if (Objects.equals(bizType, value.getBizType())) {
                    return value;
                }
            }
            return null;
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring Bean 注入示例

          本文链接:https://www.haomeiwen.com/subject/nrzuzrtx.html