Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

我利用Spring 类优化了一下 #2

Open
lhsaq2009 opened this issue Mar 8, 2020 · 0 comments
Open

我利用Spring 类优化了一下 #2

lhsaq2009 opened this issue Mar 8, 2020 · 0 comments

Comments

@lhsaq2009
Copy link

lhsaq2009 commented Mar 8, 2020

不太信任:ClassScaner.java 和 BeanTool.java 这两个类

public interface AbstractOrderHandler {
    String handle(OrderDTO dto);
    String type();
}
@Component
public class LitbHandler implements AbstractHandler {

    @Override
    public String handle(OrderDTO dto) {
        return OrderType.litb.toString();
    }

    @Override
    public String type() {
        return OrderType.litb.toString();
    }
}
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    public ApplicationContext applicationContext;

    @Override
    public String handle(OrderDTO dto) {
        String orderType = String.valueOf(dto.getType());

        // Spring 有个 Map Cache 根据 class 来缓存 bean Name, 此处无需担忧性能
        Map<String, AbstractOrderHandler> beans = applicationContext.getBeansOfType(AbstractOrderHandler.class);
        beans.values().stream()
                .filter(x -> x.type().equals(orderType))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("not found handler for type: " + orderType))
                .handle(dto);

        return null;
    }
}

后来发现用 注解 有点脱了裤子放屁的感觉。
绕来绕去的,除了增加阅读复杂度

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant