ConfiguredStrategyAdvice.java

package com.tradecloud.infrastructure.configuration;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Reusable method intercepter that loads a bean definition out of the
 * multi-tenant configuration based on the key and the logged in entity.
 */
public final class ConfiguredStrategyAdvice implements org.aopalliance.intercept.MethodInterceptor, ApplicationContextAware {

    private static Logger logger = Logger.getLogger(ConfiguredStrategyAdvice.class);

    /**
     * The key to read out of the configuration file.
     */
    private final String key;

    /**
     * The multi-tenant configuration container.
     */
    private final Configuration configuration;

    /**
     * The spring application context used to lookup the implementation
     * configured.
     */
    private ApplicationContext context;

    public ConfiguredStrategyAdvice(final String key, final Configuration configuration) {
        this.key = key;
        this.configuration = configuration;
    }

    /**
     * {@inheritDoc}
     * 
     * Example: Given key tradecloud-datasource lookup/get the bean name from
     * the client config file (edc.xml for example): edc.tradecloud.dataSource.
     * 
     * Then instantiate the bean
     */
    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        String beanName = configuration.getString(key);
        Object target = context.getBean(beanName);
        Object result = invocation.getMethod().invoke(target, invocation.getArguments());
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) {
        context = applicationContext;
    }

}