EJB stateless - Private members initialisation

牧云@^-^@ 提交于 2019-12-12 17:04:45

问题


I'm new to EJB and I'm facing my first problem. I'm trying to use an @Schedule method contained in a Stateless EJB. I'd like this method to use a private member variable which would be set at bean creation:

Here's a short example:

@Singleton
@LocalBean
@Startup
public class Starter {

     @PostActivate
     private void postActivate() {

         ScheduleEJB scheduleEjb = new ScheduleEJB("Hello");

     }

}

And the schedule bean:

@Stateless
@LocalBean
public class ScheduleEJB {

     private String message;

     public ScheduleEJB() {
         super();
     }

     public ScheduleEJB(String message) {
         super();
         this.message= message;
     }

     @Schedule(second="*/3", minute="*", hour="*", dayOfMonth="*", dayOfWeek="*", month="*", year="*")
     private void printMsg() {

         System.out.println("MESSAGE : " + message);
     }
 }

The problem is that my "message" variable is always null when printed in the printMsg() method... What's the best way to achieve this?

Thanks for your help !


回答1:


You're mixing few things here.

  1. The @PostActivate annotation is to be used on Stateful Session Beans (SFSB), and you use it on the singleton. I guess that you mean the @PostConstruct method which applies to every bean which lifecycle is managed by the container.

  2. You're using a constructor from your EJB. You cannot do:

    ScheduleEJB scheduleEjb = new ScheduleEJB("Hello");
    

    as it creates just an instance of this class. It's not an EJB - the container didn't create it, so this class does not have any EJB nature yet. That's the whole point of dependency injection - you just define what you want and the container is responsible for providing you with an appropriate instance of the resource.

  3. The Stateless Bean (SLSB) is not intented to hold the state. The SFSB is. Even if you would set the message in one SLSB method (i.e. in some ScheduleEJB#setMessage(String) method) than you need to remember that the EJB's are pooled. You don't have any guarantee that the next time you invoke a method on the ScheduleEJB you will get to the same instance.

In your case it would be the easies solution just to add the @Schedule method to your singleton class. Than you can define the variable of your choice in the @PostConstruct method. You can be sure that there is only one Singleton instance per JVM, so your variable will be visible in the Schedule annotated method of the same class.

HTH.



来源:https://stackoverflow.com/questions/7847853/ejb-stateless-private-members-initialisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!