Search code examples
ejbcdi

Starting a EJB dependency in CDI project


Well, i need use @Schedule (EJB) to put a task in crontab. I know that CDI dont have this (unhappy), just EJB. All my beans are CDI-Managed, so i have some doubts to include EJB inside this project, i hope that you can help me:

1) I'll create a new bean to use @Schedule, but i dont know if this bean should use @Singleton (EJB) or @Named + @RequestScoped (CDI). My ideia is that:

@Singleton
public class RoboFtp implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Inject
    private VideoBOImpl videoBO;

    @Schedule(...)
    public void coletarVideo(){
        //do something each 3 seconds
    }

}

Note that i have a CDI Bean inside a EJB Bean, this is possible ? This above bean is correct ?

2) How can i add the ejb to my pom.xml ?

3) If i add EJB to my project can have any conflicts ? Because my project is already in production.


Solution

  • To dispel your worries:

    1) CDI Bean inside a EJB Bean, this is possible ?

    CDI && EJB works pretty well together. In fact CDI will detect EJB beans and turn them into CDI beans as well. So if you create, say @Stateful bean, it will be picked up as CDI bean as well. That means you will be able to perform any CDI-related magic there while still having EJB features.

    As for choice of annotation, @Singleton sounds reasonable; or probably @Stateful?. @RequestScoped would only live during request and die afterwards hence killing your periodic task. Choose scope based on nature of your task (one bean vs many/ short lived vs permanent/ ..). Just make sure you make it an EJB bean and CDI will follow.

    2) How can i add the ejb to my pom.xml ?

    Assuming you have Maven project, add a dependency on EJB api, the implementation will be provided by your Java EE application server.

    <dependency>
      <groupId>javax.ejb</groupId>
      <artifactId>ejb-api</artifactId>
      <version>${desiredVersion}</version>
    </dependency>
    

    3) If i add EJB to my project can have any conflicts ?

    Too general question I am afraid; I do not know your project. But I'll go ahead and say "no". At least as far as CDI and EJB goes, you should be able to deal with it.