`

spring getBeansOfType

 
阅读更多

原创转载请注明出处:https://agilestyle.iteye.com/blog/2438883

 

前期准备:spring boot环境搭建完毕

 

Project Directory


 

AResponseData

package org.fool.springboot.contract.response;

public class AResponseData {
}

 

BResponseData

package org.fool.springboot.contract.response;

public class BResponseData {
}

 

CResponseData

package org.fool.springboot.contract.response;

public class CResponseData {
}

 

HandlerTypeEnum

package org.fool.springboot.handler;

public enum HandlerTypeEnum {
    /**
     * A(0), B(1), C(2);
     */
    A(0), B(1), C(2);

    private int index;

    public int getIndex() {
        return index;
    }

    HandlerTypeEnum(int index) {
        this.index = index;
    }
}

 

Message

package org.fool.springboot.contract;

import org.fool.springboot.handler.HandlerTypeEnum;

public class Message {
    private HandlerTypeEnum type;

    public HandlerTypeEnum getType() {
        return type;
    }

    public void setType(HandlerTypeEnum type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Message{" +
                "type=" + type +
                '}';
    }
}

 

AbstractHandler

package org.fool.springboot.handler;

public abstract class AbstractHandler<REQUEST, RESPONSE> {
    public abstract HandlerTypeEnum getHandlerType();

    protected abstract void preHandle(REQUEST request);

    protected abstract RESPONSE postHandle(REQUEST request);

    protected abstract void afterCompletion(REQUEST request, RESPONSE response);

    public void execute(REQUEST request) {
        preHandle(request);
        RESPONSE response = postHandle(request);
        afterCompletion(request, response);
    }

}

 

AHandler

package org.fool.springboot.handler;

import org.fool.springboot.contract.Message;
import org.fool.springboot.contract.response.AResponseData;
import org.springframework.stereotype.Service;

@Service
public class AHandler extends AbstractHandler<Message, AResponseData> {
    @Override
    public HandlerTypeEnum getHandlerType() {
        return HandlerTypeEnum.A;
    }

    @Override
    protected void preHandle(Message request) {
        System.out.println("AHandler pre handle sth...");
    }

    @Override
    protected AResponseData postHandle(Message request) {
        System.out.println("AHandler post handle sth...");
        // handle business logic
        return new AResponseData();
    }

    @Override
    protected void afterCompletion(Message request, AResponseData response) {
        System.out.println("AHandler after completion sth...");
    }
}

 

BHandler

package org.fool.springboot.handler;

import org.fool.springboot.contract.Message;
import org.fool.springboot.contract.response.BResponseData;
import org.springframework.stereotype.Service;

@Service
public class BHandler extends AbstractHandler<Message, BResponseData> {
    @Override
    public HandlerTypeEnum getHandlerType() {
        return HandlerTypeEnum.B;
    }

    @Override
    protected void preHandle(Message request) {
        System.out.println("BHandler pre handle sth...");
    }

    @Override
    protected BResponseData postHandle(Message request) {
        System.out.println("BHandler post handle sth...");
        // handle business logic
        return new BResponseData();
    }

    @Override
    protected void afterCompletion(Message request, BResponseData response) {
        System.out.println("BHandler after completion sth...");
    }
}

 

CHandler

package org.fool.springboot.handler;

import org.fool.springboot.contract.Message;
import org.fool.springboot.contract.response.BResponseData;
import org.fool.springboot.contract.response.CResponseData;
import org.springframework.stereotype.Service;

@Service
public class CHandler extends AbstractHandler<Message, CResponseData> {
    @Override
    public HandlerTypeEnum getHandlerType() {
        return HandlerTypeEnum.C;
    }

    @Override
    protected void preHandle(Message request) {
        System.out.println("CHandler pre handle sth...");
    }

    @Override
    protected CResponseData postHandle(Message request) {
        System.out.println("CHandler post handle sth...");
        // handle business logic
        return new CResponseData();
    }

    @Override
    protected void afterCompletion(Message request, CResponseData response) {
        System.out.println("CHandler after completion sth...");
    }
}

 

HandlerFactory

package org.fool.springboot.handler;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class HandlerFactory implements ApplicationContextAware {

    private static Map<HandlerTypeEnum, AbstractHandler> handlerMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AbstractHandler> beanMap = applicationContext.getBeansOfType(AbstractHandler.class);
        beanMap.forEach((key, value) -> handlerMap.put(value.getHandlerType(), value));
    }

    public static <T extends AbstractHandler> T getHandler(HandlerTypeEnum type) {
        return (T) handlerMap.get(type);
    }
}

 

MessageService

package org.fool.springboot.service;

import org.fool.springboot.contract.Message;

public interface MessageService {
    void handleMessage(Message message);
}

 

MessageServiceImpl

package org.fool.springboot.service.impl;

import org.fool.springboot.contract.Message;
import org.fool.springboot.handler.AbstractHandler;
import org.fool.springboot.handler.HandlerFactory;
import org.fool.springboot.handler.HandlerTypeEnum;
import org.fool.springboot.service.MessageService;
import org.springframework.stereotype.Service;

@Service
public class MessageServiceImpl implements MessageService {
    @Override
    public void handleMessage(Message message) {
        HandlerTypeEnum type = message.getType();

        AbstractHandler handler = HandlerFactory.getHandler(type);

        handler.execute(message);
    }
}

 

MessageController

package org.fool.springboot.controller;

import org.fool.springboot.contract.Message;
import org.fool.springboot.handler.HandlerTypeEnum;
import org.fool.springboot.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/msgA")
    public String msgA() {
        Message message = new Message();
        message.setType(HandlerTypeEnum.A);

        messageService.handleMessage(message);

        return "SUCCESS";
    }

    @GetMapping("/msgB")
    public String msgB() {
        Message message = new Message();
        message.setType(HandlerTypeEnum.B);

        messageService.handleMessage(message);

        return "SUCCESS";
    }

    @GetMapping("/msgC")
    public String msgC() {
        Message message = new Message();
        message.setType(HandlerTypeEnum.C);

        messageService.handleMessage(message);

        return "SUCCESS";
    }
}

 

Test

http://localhost:8088/v1/msgC


Console Output


 

  • 大小: 145.3 KB
  • 大小: 20.6 KB
  • 大小: 147.8 KB
分享到:
评论

相关推荐

    Spring3新特性

    例如,`T getBean(String name, Class&lt;T&gt; requiredType)` 和 `Map, T&gt; getBeansOfType(Class&lt;T&gt; type)` 方法的加入使得操作更加直观和安全。 2. **TaskExecutor接口更新** TaskExecutor接口继承自`java.util....

    spring 学习 interfaces例子

    例如,`getBean()`方法用于获取指定名称的Bean实例,`getBeansOfType()`则可以获取所有指定类型的Bean。 2. `BeanFactory`:它是`ApplicationContext`的父接口,提供更底层的Bean管理功能。虽然在实际开发中通常...

    第五章 Spring 依赖查找1

    在Spring框架中,依赖注入(Dependency Injection,简称DI)是一种重要的设计模式,它允许对象间的依赖关系被外部容器管理,而不是由对象自身负责。Spring IoC(Inversion of Control)容器是实现DI的核心组件。本章...

    韩顺平Spring笔记

    从`ApplicationContext`中获取Bean有两种方式:通过`getBean(String beanId)`获取指定ID的Bean,或者通过`getBeansOfType(Class&lt;?&gt; requiredType)`获取所有指定类型的Bean。 总的来说,Spring框架通过提供IoC和DI,...

    39.3 Spring Boot Shiro权限管理【从零开始学Spring Boot】

    在本主题中,我们将深入探讨如何使用Spring Boot与Apache Shiro进行权限管理。Spring Boot以其简洁的配置和快速的应用开发特性,已经成为了Java领域中的热门框架。而Shiro则是一款强大的安全框架,提供了身份验证、...

    学习Spring的一点代码01:如何获取bean?

    `ApplicationContext`提供了多个变体的`getBean`方法,如`getBean(String)`,`getBean(Class)`和`getBeansOfType(Class)`。后者可以获取所有匹配类型的Bean。 6. **`BeanFactory`接口** 如果你不需要完整的...

    spring如何动态指定具体实现类

    Map, ServiceInterface&gt; beanMap = applicationContext.getBeansOfType(ServiceInterface.class); for (ServiceInterface serviceImpl : beanMap.values()) { serviceImplMap.put(serviceImpl.toString(), ...

    Spring Boot中的那些条件判断的实现方法

    Map, Person&gt; map = applicationContext.getBeansOfType(Person.class); System.out.println(map); } } ``` 输出的结果: 当前系统为:Mac OS X {linus=Person(name=Linus, age=48)} 从上面的示例可以看到,...

    Spring注解@Conditional案例解析

    Map, Person&gt; map = applicationContext.getBeansOfType(Person.class); System.out.println(map); } } ``` 测试结果: ``` {bill=Person{name='Bill Gates',age=62},linus=Person{name='Linus',age='48'}} ``` ...

    Java获取接口所有实现类的方式详解

    map = applicationContext.getBeansOfType(IService.class); } public Map, IService&gt; getMap() { return map; } } ``` 在上面的代码中,我们使用了 Spring 的 `ApplicationContext` 来获取所有的接口实现类...

Global site tag (gtag.js) - Google Analytics