How to integrate Spring and JSF

advertisements

This question already has an answer here:

  • Spring JSF integration: how to inject a Spring component/service in JSF managed bean? 2 answers

How to integrate Spring and JSF? I followed Spring documentation (which is sparse on this subject) and googled some more and currently I found two working ways:

  1. JSF Managed Bean will be Spring @Component / @Named (but there doesn't seem to work JSF scopes, but only Spring scopes):

    @Component
    @Scope("request")
    public class ItemController {
    
      @Autowired
      private ItemService itemService;
    
    }
    
    
  2. I will use @ManagedBean, JSF scopes work, but I cannot autowire Spring bean using @Autowired, the bean must contain setter and I'm not sure if this is best practice:

    @ManagedBean
    @RequestScoped
    public class ItemController {
    
      @ManagedProperty("#{itemService}")
      private ItemService itemService;
    
      public void setItemService(ItemService itemService) {
        this.itemService = itemService;
      }
    
    }
    
    
  3. Something else?


I would definitely go with way number 1 (and did so in quite some projects). It makes no real sense to mix JSF managed beans with Spring beans, unless you have a good reason to do so. With Spring managed beans, you have far more possibilities and you can use the full power of Spring even for your managed beans.

Theoretically, there is a third way: You could use CDI for the UI layer and Spring in the background. This might be an option if you don't want to use a full blown Java EE environment but still want to benefit from CDI and Myfaces CODI/Deltaspike in the UI layer. But in this case you would additionally need a CDI setup and a CDI to Spring bridge.