Injecting a Spring bean using CDI @Inject

前端 未结 3 907
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题