Injecting a Spring bean using CDI @Inject

Solution 1:

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.

Solution 2:

I don't think Weld can inject something that is not managed (instantiated) by Weld (a Spring bean in your case).

Solution 3:

There's also the JBoss Snowdrop project. I don't know if it'll work with JBoss Weld on Tomcat, the documentation describes only on JBoss 5, 6 and 7. According to http://docs.jboss.org/snowdrop/2.0.0.Final/html/ch03.html#d0e618 it will inject beans declared in jboss-spring.xml into locations marked with @Spring instead of @Inject. No experience myself though, YMMV.