0
我有一個叫做RandomBean
的SFSB,它有一個默認構造函數@PostConstruct
,@PreDestroy
和@Remove
方法。在構造函數中有一個簡單的計數器。InitialContext.doLookup調用Bean的構造函數兩次
@Stateful
public class RandomBean {
public static int c = 0;
public static final Logger logger = Logger.getLogger(RandomBean.class);
private Random r;
private int cc;
public RandomBean() {
c += 1;
cc = c;
r = new Random();
logger.info("Random constructed: " + cc);
}
@PostConstruct
public void init() {
logger.info("Random started: " + cc);
}
public int nextInt() {
logger.info("Random invoked: " + cc);
return r.nextInt();
}
@PreDestroy
public void destroy() {
logger.info("Random destroyed: " + cc);
}
@Remove
public void remove() {
logger.info("removed: " + cc);
}
}
我也有對這個bean執行查找和調用其nextInt
方法的servlet。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Doing get");
try {
RandomBean r = InitialContext.doLookup("java:module/RandomBean");
logger.info("get! " + r.nextInt());
r.remove();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
什麼讓我困惑的是,RandomBean
的構造似乎叫了兩聲:
02:13:09,558 INFO [org.sokolas.model.HelloServlet] (http-localhost/127.0.0.1:8080-1) Doing get
02:13:09,559 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random constructed: 1
02:13:09,560 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random constructed: 2
02:13:09,561 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random started: 2
02:13:09,561 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random invoked: 2
02:13:09,562 INFO [org.sokolas.model.HelloServlet] (http-localhost/127.0.0.1:8080-1) get! -2028573462
02:13:09,562 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) removed: 2
02:13:09,563 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random destroyed: 2
這種行爲是故意的嗎?我應該把所有的初始化放在@PostConstruct
方法中,而不要使用構造函數嗎? 我正在使用JBoss EAP 6.2。