如何避免从上下文中检索 Spring 托管 bean

How to avoid retrieving a Spring managed bean from the context

我的应用程序接收消息、提取数据并将提取的数据保存到数据库中。数据通过 Apache Camel 通道接收,添加到 FIFO。以下代码从 FIFO 中获取下一条消息并对其进行处理。但是,为了做到这一点,它需要从 Spring 应用程序上下文中获取一个 bean:

private static void dispatch(Message msg) {
                if (msg == null) {
                    return;
                }
                // TODO: This really violates IoC.
                DomainObjectFactory factory = (DomainObjectFactory) ApplicationContextProvider.getApplicationContext().getBean("domainObjectFactoryBean", DomainObjectFactory.class);

            // do something with message

这是服务 class:

@Service
public class ApplicationContextProvider implements ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(ApplicationContextProvider.class);

    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return getCtx();
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        log.debug("Loading context");
        ApplicationContextProvider.setCtx(ctx);
    }

    public static ApplicationContext getCtx() {
        return ctx;
    }

    public static void setCtx(ApplicationContext ctx) {
        ApplicationContextProvider.ctx = ctx;
    }
}

正在从 FIFO 中读取消息:

    void process(Object obj) {
        Message msg = (Message) obj;
        try {
            Dispatcher.process(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这确实是一个弱代码,但我不知道如何避免它?那就是如何使用 Spring IoC 来 link 从 FIFO 中移除消息以进行消息处理,而不必从上下文中检索 bean。

感谢任何建议/指导

当然,如果您使用注解或基于 xml 的注入,您的代码看起来会好很多。如果您的 dispatch 方法不是静态的,这会更容易。不过,您可以使用 MethodInvokingFactoryBean 将 Spring beans 注入静态字段。在这里查看更多信息: