我正在尝试使用嵌入式tomcat服务器中的JNDI配置端点服务URL(我将从在Spring Boot中编写的其余服务中调用该端点)。但是我不能这样做,因为它引发了classcastexception。无法从代理转换为URL
例外:
Caused by: java.lang.ClassCastException: com.sun.proxy.$Proxy51 cannot be cast to java.net.URL
at io.javabrains.boot.ApplicationStarter.jndiDataSource(ApplicationStarter.java:85) [classes/:na]
at io.javabrains.boot.ApplicationStarter$$EnhancerBySpringCGLIB$$59e10b3.CGLIB$jndiDataSource$0(<generated>) ~[classes/:na]
at io.javabrains.boot.ApplicationStarter$$EnhancerBySpringCGLIB$$59e10b3$$FastClassBySpringCGLIB$$90c9344c.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
@Bean
public TomcatServletWebServerFactory servletContainerV2() {return new TomcatServletWebServerFactory() {
@Override
protected TomcatWebServer
getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
resource.setName("jdbc/myJndiResource");
resource.setType(URL.class.getName());
URL url = "www.google.com"
resource.setProperty("url",url)
context.getNamingResources().addResource(resource);
}
================================================ ==========
@Bean
public URL jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:/comp/env/jdbc/myJndiResource");
bean.setExpectedType(URL.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
URL url = (URL)bean.getObject();
}
我将能够从jndiDataSource获取URL,该URL可以基于运行环境(例如dev,staging等)在运行时注入到我的服务bean中。