Injecting a Spring bean using CDI @Inject

前端 未结 3 905
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 08:35

I\'m trying to inject a bean defined in a Spring context into a CDI managed component but I\'m not successful. The bean is not injected, instead a new instance gets created

相关标签:
3条回答
  • 2020-12-03 09:14

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

    0 讨论(0)
  • 2020-12-03 09:15

    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.

    0 讨论(0)
  • 2020-12-03 09:18

    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.

    0 讨论(0)
提交回复
热议问题