我有一个基于Spring的基于Web的应用程序,它具有使用JNDI定义的数据源,我正在尝试创建一个独立的应用程序来使用bean.如何在独立应用程序中以编程方式创建JNDI条目和数据库属性?
diobjectfactorybean">
编辑:
我尝试过类似的东西,但现在收到错误“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();
}
}
最佳答案
org.springframework.test依赖项通过
SimpleNamingContextBuilder
支持:
// First create the mock JNDI tree and bind the DS
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
DataSource ds = new ComboPooledDataSource();
ds.setDriverClass( ... ); // etc. for uid,password,url
builder.bind( "java:comp/env/jdbc/MyDS",ds );
builder.activate();
// Then create the Spring context,which should now be able
// to resolve the JNDI datasource
ApplicationContext context = new ClassPathXmlApplicationContext( "..." );
这应该工作.
干杯,