我有了使用JNDI数据源定义一个Spring的基于Web的应用程序,我想创建一个独立的应用程序使用的bean。 我怎样才能在独立的应用程序编程方式创建JNDI条目和数据库性能?
<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/MyDS" />
</bean>
public static void main(String[] args) {
// this throws an error since the JNDI lookup fails - can I programmatically define the database properties here?
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = ctx.getBean(UserService.class);
User user = userService.findUserById("jdoe");
System.out.println("display name: " + user.getDisplayName());
}
编辑:
我想这样的事情,但我现在得到的错误“javax.naming.NoInitialContextException:需要环境或系统属性指定的类名”
public static void main(String[] args) {
setupJNDI();
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = ctx.getBean(UserService.class);
User user = userService.findUserById("jdoe");
System.out.println("display name: " + user.getDisplayName());
}
private static void setupJNDI() {
InitialContext ic;
try {
ic = new InitialContext();
ic.createSubcontext("java:");
ic.createSubcontext("java:/comp");
ic.createSubcontext("java:/comp/env");
ic.createSubcontext("java:/comp/env/jdbc");
SQLServerConnectionPoolDataSource myDS = new SQLServerConnectionPoolDataSource();
opaDS.setServerName("myserver");
opaDS.setPortNumber(1433);
opaDS.setUser("user");
opaDS.setPassword("password");
ic.bind("java:/comp/env/jdbc/MyDS", myDS);
} catch (NamingException e) {
e.printStackTrace();
}
}