Skip to content
Advertisement

Spring 5.x and CDI 2.x Integration Options

Considering Spring’s 5.x baseline and CDI’s baseline 2.x, what more viable options should I consider to integrate them into a project with JSF 2.3, since JSF 2.3 is coupled with the CDI? Bridges? Custom Bean Factories? Others?

Advertisement

Answer

We use bean producers to access Spring objects in CDI. As in the architecture we used there is an interface layer between the UI and the server/business, this integration was facilitated. Integration is performed as follows.

Cdi Factory from the view/ui layer.

public class MainViewClientFactory {

    public MainViewClientFactory() {
    }

    @ApplicationScoped
    @Produces
    public CadastroPaisService cadastroPaisService() {
        return CdiSpringUtils.getSpringBean(CadastroPaisService.class);
    }

}

The CdiSpringUtils Class.

public class CdiSpringUtils {

    private CdiSpringUtils() {
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass) {
        return ApplicationContextProvider.getApplicationContext().getBean(beanClass);
    }

    public static <R, Q extends Annotation> R getSpringBean(Class<R> beanClass, Class<Q> qualifierClass) {
        return ApplicationContextProvider.getQualifiedBeanOfType(beanClass, qualifierClass);
    }

}

The ApplicationContextProvider Class.

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <R, Q extends Annotation> R getQualifiedBeanOfType(Class<R> cls, Class<Q> qualifierAnnotationClass) {
        R bean = null;
        Map<String, R> beanMap = getApplicationContext().getBeansOfType(cls);
        for (Map.Entry<String, R> entry : beanMap.entrySet()) {
            Q targetAnnotation = getApplicationContext().findAnnotationOnBean(entry.getKey(), qualifierAnnotationClass);
            if (targetAnnotation != null) {
                bean = entry.getValue();
                break;
            }
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        context = ctx;
    }
}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement