0

My application receives messages, extracts data and persists the extracted data to a database. Data is received via a Apache Camel channel, added to a FIFO. The following code takes the next message from the FIFO and processes it. However, in order to do this it needs to get a bean from the Spring application context:

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

This is the service 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;
    }
}

reading a message from the FIFO:

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

This is really weak code, but I can't work out how to avoid it? That is how to use Spring IoC to link the removal of a message from the FIFO to the message processing without having to retrieve the bean from the context.

Any advice / guidance appreciated

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
skyman
  • 2,255
  • 4
  • 32
  • 55
  • Inject the bean into your camel rout builder or processor or whatever. Stop using static methods for everything. – JB Nizet May 04 '15 at 11:18
  • ok - I am fairly new to Ioc. 1) what is wrong with static methods? (I am trying to learn here) & 2) I am not exactly sure how to inject the bean. I have added the code that reads from the FIFO (which runs in a different thread from the Camel code that writes to the FIFO) – skyman May 04 '15 at 11:31

1 Answers1

1

Naturally, your code would look a whole lot nicer, if you would use annotation or xml-based injection. This would be easier, if your dispatch method was not static. Still, you can inject Spring beans into static fields utilizing a MethodInvokingFactoryBean. Look here for more information:

How can I inject local variables of a static method inside an abstract class using Spring?

Community
  • 1
  • 1
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60