有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数据源。EBJ3会话bean中的getConnection()

在使用EJB3无状态会话bean时,哪里是获得注入数据源连接的最佳位置?我有一个调用ds的方法。getConnection(),但这种情况每次都会发生,因此为每次调用打开和关闭连接既不经济也不明智

通常最好将数据源连接的访问和关闭放在托管生命周期方法中吗?我希望确保以尽可能低的成本访问数据源,同时确保在不再需要连接时关闭连接,这样它就不会只是挂起打开

谢谢


共 (1) 个答案

  1. # 1 楼答案

    The Lifecycle of a Stateless Session Bean

    Because a stateless session bean is never passivated, its lifecycle has only two stages: nonexistent and ready for the invocation of business methods. Figure 22-4 illustrates the stages of a stateless session bean.

    Diagram showing the lifecycle of a stateless session bean.

    The EJB container typically creates and maintains a pool of stateless session beans, beginning the stateless session bean’s lifecycle. The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The bean is now ready to have its business methods invoked by a client.

    At the end of the lifecycle, the EJB container calls the method annotated @PreDestroy, if it exists. The bean’s instance is then ready for garbage collection.

    Source: http://docs.oracle.com/javaee/6/tutorial/doc/giplj.html

    在EJB中创建一个字段来存储在@PostConstruct获得的连接实例,然后在@PreDestroy中释放它

    下面是这个http://theopentutorials.com/tutorials/java-ee/ejb3/session-beans/slsb/stateless-session-beans-lifecycle-callback-methods/的编写代码示例