Injecting a Spring bean using CDI @Inject

Pascal is right that you can’t inject something managed by spring into a weld bean (or vice-versa).

But you can define a producer that gets spring beans and gives them to Weld. This sounds like an extreme hack, btw, and I don’t think you are supposed to use both frameworks in one project. Choose one and remove the other. Otherwise you’ll get in multiple problems.

Here’s how it would look like.

@Qualifier
@Retention(Runtime)
public @interface SpringBean {
     @NonBinding String name();
}


public class SpringBeanProducer {

    @Produces @SpringBean
    public Object create(InjectionPoint ip) {
         // get the name() from the annotation on the injection point
         String springBeanName = ip.getAnnotations()....

         //get the ServletContext from the FacesContext
         ServletContext ctx = FacesContext.getCurrentInstance()... 

         return WebApplicationContextUtils
              .getRequiredWebApplication(ctx).getBean(springBeanName);
    }
}

Then you can have:

@Inject @SpringBean("fooBean")
private Foo yourObject;

P.S. You can make the above more type-safe. Instead of getting the bean by name, you can get, through reflection, the generic type of the injection point, and look it up in the spring context.

Leave a Comment