尝试创建计时器时出现 NullPointerException。显然 TimerService 没有设置,但我的问题是,为什么?据我所知,我正在遵循我们应用程序中另一个类使用的确切模式,该模式确实有效。
注意:我是 EJB 新手,所以解释很有帮助
@Stateless
public class MyClass implements SomeInterface
{
private static final Logger ourLogger = new Logger(MyClass.class);
private volatile Timer timer = null;
private volatile static MyClass instance = null;
@javax.annotation.Resource
TimerService timerService;
@Override
public synchronized void myMethod()
{
resetTimer();
//do other stuff
}
/**
* Creates the timer.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private synchronized void resetTimer()
{
if (timer != null)
{
timer.cancel();
timer = null;
}
//NullPointerException on next line:
timer = timerService.createTimer(30000, "My Note");
}
public static MyClass getInstance()
{//MDB calls this, then runs instance.myMethod
if (instance == null)
{
instance = new MyClass ();
}
return instance;
}
@Timeout
public synchronized void timeout()
{
//Do some stuff
instance = null;
}
}