javax.naming.NameNotFoundException:在WebSphere Liberty上

问题描述 投票:1回答:2

我正在尝试在WebSphere Application Server Liberty上使用配置为JNDI的数据源但是我收到以下错误:

javax.naming.NameNotFoundException: java:comp/env/jdbc/myapp/master

Websphere应用程序服务器中数据源的配置是:

<dataSource commitOrRollbackOnCleanup="commit" id="jdbc/myapp/master" jdbcDriverRef="ojdbc7" jndiName="jdbc/myapp/master">
        <properties.oracle URL="jdbc:oracle:thin:@127.0.0.1:1521:xe" oracleRACXARecoveryDelay="0" password="xxxxxxxx" user="app_master"> 
         </properties.oracle>
         <connectionManager maxPoolSize="50"/>
    </dataSource>

与数据库的连接是通过servlet中的代码进行的(jndi = jdbc / myapp / master):

Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource) envCtx.lookup(jndi);
            setConnection(ds.getConnection());
            System.out.println(getConnection().toString() );    

我究竟做错了什么?

java datasource jndi websphere-liberty
2个回答
3
投票

java:comp/env需要资源参考。您有以下选项可以解决这个问题:

1)使用资源注入 - 所以不要直接查找它(通过InitialContext),只需在servlet类中添加以下内容即可

@Resource(lookup = "jdbc/myapp/master", name="jdbc/myapp/master")
private DataSource dataSource;

2)在你的web.xml中定义资源引用

<resource-ref>
   <description>my datasource</description>
   <res-ref-name>jdbc/myapp/master</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>CONTAINER</res-auth>
</resource-ref>

或者您也可以通过代码中的注释创建引用。

3)使用直接JNDI,无需参考(不是Java EE最佳实践)

 DataSource ds = (DataSource) initCtx.lookup("jdbc/myapp/master");

1
投票

除了在其他答案中已经说明的内容之外,您还应该检查是否已启用jndi-1.0功能。这是查找无法在Liberty中工作的常见原因。

例如,在server.xml中,

<featureManager>
  <feature>jdbc-4.2</feature>
  <feature>jndi-1.0</feature>
  ... other features that you use
</featureManager>

如果这也不足以让它工作,你还应该检查dataSource所依赖的资源配置,例如id为ojdbc7的jdbcDriver,它在你提供的配置代码段中引用。

© www.soinside.com 2019 - 2024. All rights reserved.