Tiles Config bean throws exception: TestNG+Spring 3+Tiles2 - spring

I'm trying to run a TestNG+Spring+JPA+Hibernate 'Hello World' test. The execution results in a NullPointerException, the tiles configurer bean fails.
The exception:
2011-08-20 18:12:18,547 [main] INFO org.springframework.web.servlet.view.tiles2.TilesConfigurer - TilesConfigurer: adding definitions [/WEB-INF/tiles/tiles.xml]
2011-08-20 18:12:18,552 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#68cb6b: defining beans [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#0,org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor#0,org.springframework.security.methodSecurityMetadataSourceAdvisor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,nethawalaDS,jspViewResolver,tilesViewResolver,tilesConfigurer,nethawalaEMF,transactionManager,jpaVendorAdapter,validator,auditLog,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,logoutHandlerBean,userDetailsService,customAuthenticationFailureHandlerBean,customAuthenticationSuccessHandlerBean,httpSessionEventListener,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.scheduling.annotation.internalAsyncAnnotationProcessor,org.springframework.scheduling.annotation.internalScheduledAnnotationProcessor,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,homeController,userSessionController,NHUserDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,nethawalaProperties,placeholderConfig]; root of factory hierarchy
2011-08-20 18:12:18,563 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#fdfc58] to prepare test instance [com.tigermindz.test.FacultyDaoTest#1afae45]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:133)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:76)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:525)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:202)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:130)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:173)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.runWorkers(TestRunner.java:1147)
at org.testng.TestRunner.privateRun(TestRunner.java:749)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:317)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:312)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:274)
at org.testng.SuiteRunner.run(SuiteRunner.java:223)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1039)
at org.testng.TestNG.runSuitesLocally(TestNG.java:964)
at org.testng.TestNG.run(TestNG.java:900)
at org.testng.TestNG.privateMain(TestNG.java:1182)
at org.testng.TestNG.main(TestNG.java:1146)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [nethawala-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
... 28 more
Caused by: java.lang.NullPointerException
at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory$SpringWildcardServletTilesApplicationContext.(SpringTilesApplicationContextFactory.java:72)
at org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory.createApplicationContext(SpringTilesApplicationContextFactory.java:55)
at org.springframework.web.servlet.view.tiles2.TilesConfigurer.afterPropertiesSet(TilesConfigurer.java:335)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 41 more
My applicationContext.xml, only showing the tiles config bean def:
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles.xml</value>
</list>
</property>
</bean>
Did a lot of googling, only thing found, people mentioned about cglib and/or asm jars in conflict with spring and hibernate dependencies. I don't think that is applicable here however my lib folder has the following jars, sorry not in order:
./tiles-template-2.2.2.jar
./spring-security-acl-3.0.5.RELEASE.jar
./org.springframework.context-3.0.5.RELEASE.jar
./hibernate-jpa-2.0-api-1.0.0.Final.jar
./tiles-api-2.2.2.jar
./validation-api-1.0.0.GA.jar
./org.springframework.web.servlet-3.0.5.RELEASE.jar
./hsqldb.jar
./spring-security-taglibs-3.0.5.RELEASE.jar
./commons-pool-1.5.6.jar
./aspectjrt-1.6.8.jar
./commons-beanutils-1.8.3.jar
./org.springframework.aop-3.0.5.RELEASE.jar
./spring-security-core-3.0.5.RELEASE.jar
./commons-collections-3.1.jar
./org.springframework.web-3.0.5.RELEASE.jar
./jstl-1.2.jar
./org.springframework.expression-3.0.5.RELEASE.jar
./dom4j-1.6.1.jar
./org.springframework.orm-3.0.5.RELEASE.jar
./log4j-1.2.16.jar
./org.springframework.beans-3.0.5.RELEASE.jar
./tiles-servlet-2.2.2.jar
./poi-3.7-20101029.jar
./spring-security-aspects-3.0.5.RELEASE.jar
./slf4j-api-1.6.1.jar
./aopalliance-1.0.jar
./slf4j-simple-1.6.1.jar
./hibernate3.jar
./slf4j-ext-1.6.1.jar
./spring-security-web-3.0.5.RELEASE.jar
./jta-1.1.jar
./asm-3.3.1.jar
./org.springframework.test-3.0.5.RELEASE.jar
./spring-security-config-3.0.5.RELEASE.jar
./org.springframework.core-3.0.5.RELEASE.jar
./org.springframework.asm-3.0.5.RELEASE.jar
./tiles-jsp-2.2.2.jar
./testng-6.0.1.jar
./commons-digester-2.1.jar
./commons-logging-1.1.1.jar
./org.springframework.transaction-3.0.5.RELEASE.jar
./javax.inject.jar
./commons-dbcp-1.4.jar
./slf4j-log4j12-1.6.1.jar
./hibernate-validator-4.1.0.Final.jar
./javassist-3.12.0.GA.jar
./tiles-core-2.2.2.jar
./aspectjweaver-1.6.8.jar
./org.springframework.jdbc-3.0.5.RELEASE.jar
./jackson-all-1.7.5.jar
./jstl-api-1.2.jar
./antlr-2.7.6.jar
./cglib-2.2.jar
The test class is as follows:
#ContextConfiguration(locations = { "classpath:test-servlet.xml" })
public class FacultyDaoTest extends AbstractTransactionalTestNGSpringContextTests {
private final XLogger logger = XLoggerFactory.getXLogger(FacultyDaoTest.class);
#Inject
FacultyDAO facultyDao;
#BeforeClass
public void setUp() {
logger.entry();
System.out.println("Inside setup");
}
#Test(groups = { "fast" })
#Rollback(value = false)
public void createFaculty() {
Faculty f = new Faculty();
f.setFirstName("John");
f.setLastName("Frost");
f.setCpsoNumber("23198");
f = facultyDao.makePersistent(f);
assert(f.getId() > 0);
}
#Test(groups = { "fast" })
public void aFastTest() {
logger.entry();
logger.info("Inside a Fast test");
}
#Test(groups = { "slow" })
public void aSlowTest() {
logger.entry();
logger.info("Inside a Slow test");
}
}
Any pointers will be greatly appreciated.

Your test load a web app specific configuration file, but your test environment does not provide the required files:
You need to separate the Web Application specific configuration from the one the works wihtout web application context.
Then use for the test the one that works without Web Application.
For you that mean: remove the Tiles Configuration for the test configuration. Because in the test the /WEB-INF/tiles/tiles.xml file is not available.

Related

Testing Apache Camel with TestNG being enabled with Spring Boot

I have created an Apache Camel project using Spring Boot where I configure the routes in a #Component annotated class.
#Component
public final class EdlRouteBuilder extends RouteBuilder {
#Override
public final void configure() throws Exception {
//here is the setup of my Camel routes
...
}
}
Additionally I have a test class which extends AbstractCamelTestNGSpringContextTests containing one test method for testing my route.
Within the test class I need to start the CamelContext manually as I need to startup an embedded FTP server prior to testing.
#ActiveProfiles("test")
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = EdlApplication.class)
#DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
#DisableJmx(false)
#UseAdviceWith
#MockEndpoints("*")
#ContextConfiguration(classes=EdlRouteBuilder.class)
public class RouteTest extends AbstractCamelTestNGSpringContextTests {
private static final Logger LOG = LoggerFactory.getLogger(RouteTest.class);
#Autowired
private CamelContext camelContext;
...
#BeforeClass
public final void beforeClass() throws Exception {
private FtpServer ftpServer;
...
}
#BeforeClass
public final void beforeClass() throws Exception {
...
}
}
Problem is that the CamelContext is not autowired but I get the following excetption:
15:56:15.438 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#6ce139a4] to prepare test instance [com.rwetrading.integration.camel.mft.edl.RouteTest#7ee955a8]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.rwetrading.integration.camel.mft.edl.RouteTest': Unsatisfied dependency expressed through field 'camelContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.camel.CamelContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:581)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:367)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1340)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:400)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:165)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:776)
at org.testng.TestRunner.run(TestRunner.java:634)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
at org.testng.SuiteRunner.run(SuiteRunner.java:334)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
at org.testng.TestNG.runSuites(TestNG.java:1161)
at org.testng.TestNG.run(TestNG.java:1129)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:132)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:193)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:94)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:147)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.camel.CamelContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1502)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1099)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1060)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:578)
... 37 common frames omitted
15:56:15.485 [main] INFO com.rwetrading.integration.camel.mft.edl.RouteTest - ********************************************************************************
15:56:15.485 [main] INFO com.rwetrading.integration.camel.mft.edl.RouteTest - Testing done: test(com.rwetrading.integration.camel.mft.edl.RouteTest)
15:56:15.487 [main] INFO com.rwetrading.integration.camel.mft.edl.RouteTest - Took: 0.001 seconds (1 millis)
15:56:15.487 [main] INFO com.rwetrading.integration.camel.mft.edl.RouteTest - ********************************************************************************

Spring boot DispatchServlet

I've a spring boot project (executable jar with embedded jetty9).
I should register 2 different DispatcherServlet. I done in this way:
#Bean
public ServletRegistrationBean dispatcherServlet() {
DispatcherServlet servlet = new DispatcherServlet();
ServletRegistrationBean sr = new ServletRegistrationBean(servlet, "/graniteamf/*");
return sr;
}
#Bean
#Order(2)
public ServletRegistrationBean customDispatcherServlet() {
DispatcherServlet servlet = new DispatcherServlet();
ServletRegistrationBean sr = new ServletRegistrationBean(servlet, "/client/*");
return sr;
}
Unfortunally when I try to start the application I've this exception:
17/02/2015 18:24:04 INFO ApacheAsyncTransport:54 - Starting Apache HttpAsyncClient transport...
17/02/2015 18:24:04 INFO ApacheAsyncTransport:54 - Apache HttpAsyncClient transport started.
17/02/2015 18:24:04 DEBUG Application:173 - Inizializzazione identity
17/02/2015 18:24:04 ERROR DispatcherServlet:497 - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:612)
at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:395)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:871)
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext$JettyEmbeddedServletHandler.deferredInitialize(JettyEmbeddedWebAppContext.java:46)
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext.deferredInitialize(JettyEmbeddedWebAppContext.java:36)
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:162)
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:109)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:287)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at it.pianetatecno.gsmgateway.Application.main(Application.java:61)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 30 more
17/02/2015 18:24:05 ERROR SpringApplication:339 - Application startup failed
org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Jetty servlet container
at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:119)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:287)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at it.pianetatecno.gsmgateway.Application.main(Application.java:61)
I've two questions:
xml file for dispatcherServlet is mandatory?
in which folder Spring expect to find this file? I tried to put it into resources/WEB-INF but it doesn't work.
Edited question
This is my main mathod in Spring Boot:
#SpringBootApplication
public class Application {
private static Logger log = Logger.getLogger(Application.class);
private static ApplicationContext context;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
context = app.run(args);
app.setShowBanner(false);
}
Thanks
You don't need XML, but you do need to set the ApplicationContext on the servlet. Spring will do that for you if it is a #Bean (as it is in the DispatcherServletAutoConfiguration in Spring Boot), or I guess you can do it manually.

Spring batch late binding for stepExecutionContext not working

I am using Spring batch application and want to use late binding for stepExecutionContext. I am facing issues in resolving my error.
Following is my reader which has sql property using late binding:
<bean id="itemReader_S4_JPolicy" class="com.aegonusa.etl.readers.JDBCItemReader" scope="step">
<property name="jobParameters" ref="jobParameters" />
<property name="dataSource" ref="readDataSource" />
<property name="rowMapper">
<bean class="com.aegonusa.etl.readers.ResultSetRowMapper" scope="step" />
</property>
<property name="sql"
value="#{stepExecutionContext['readQuery']}"></property>
</bean>
I set this property ('readQuery') in following class:
public class StepListener implements StepExecutionListener
{
....
....
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate();
StepSynchronizationManager.getContext().setAttribute("readQuery", s);
.....
}
.....
}
Please note that I am able to do late binding using jobParameters.
But using stepExecutionContext, I get following exc. I tried lot of posts in forums but am unable to resolve it:
Throwable occurred: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lazyBindingProxy.itemReader_S4_JPolicy#sysinit' defined in class path resource [Load_InforceToStage.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:224)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:302)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.batch.core.scope.util.PlaceholderTargetSource.getTarget(PlaceholderTargetSource.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at $Proxy1.close(Unknown Source)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.item.ChunkMonitor.close(ChunkMonitor.java:99)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:297)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:255)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:49)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:349)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:574)
at com.ebsadm.lh.LHSHEDToStage.runJob(LHSHEDToStage.java:124)
at com.ebsadm.lh.LHSHEDToStage.main(LHSHEDToStage.java:111)
at com.ebdadm.lh.TestLHSHEDToStage.testInforceLoadToStage(TestLHSHEDToStage.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.batch.core.scope.util.PlaceholderTargetSource$1.convertIfNecessary(PlaceholderTargetSource.java:140)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1294)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
... 50 more
Kindly help.
I would expect a call to getExecutionContext on the StepExecution to give you the proper context.
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate()";
execution.getExecutionContext().putString("readQuery", s);
}
Your current solution is getting the StepContext. The StepContext is the object that is exposed and used for expression parsing, whereas the ExecutionContext associated with the StepExecution is the actual stepExecutionContext. ItemReaders and ItemWriters and such object also use the ExecutionContext to update the state (skipped items, commit count etc.).
Try any of the below :
Use promotionListener bean to promote the scope of variable from step to job.
Use bean instead of executionContext.

Hibernate/Spring - AnnotationSessionFactoryBean - how to resolve duplicate import?

I'm having a problem in a Spring Configuration creating a bean which extends AnnotationSessionFactoryBean.
Here's the definition of the class:
public class ExtendedAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean {
private String[] basePackages;
private ClassLoader beanClassLoader;
#Override
public void afterPropertiesSet() throws Exception {
System.out.println("ExtendedAnnotationSessionFactoryBean, in afterPropertiesSet");
Collection<Class<?>> entities = new ArrayList<Class<?>>();
ClassPathScanningCandidateComponentProvider scanner = this.createScanner();
for (String basePackage : this.basePackages) {
this.findEntities(scanner, entities, basePackage);
}
this.setAnnotatedClasses(entities.toArray(new Class<?>[entities.size()]));
super.afterPropertiesSet();
}
private ClassPathScanningCandidateComponentProvider createScanner() {
System.out.println("ExtendedAnnotationSessionFactoryBean, in createScanner");
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
return scanner;
}
private void findEntities(ClassPathScanningCandidateComponentProvider scanner,
Collection<Class<?>> entities, String basePackage) {
System.out.println("ExtendedAnnotationSessionFactoryBean, in findEntities");
Set<BeanDefinition> annotatedClasses = scanner.findCandidateComponents(basePackage);
for (BeanDefinition bd : annotatedClasses) {
String className = bd.getBeanClassName();
System.out.println("ExtendedAnnotationSessionFactoryBean, className: " + className);
Class<?> type = ClassUtils.resolveClassName(className, this.beanClassLoader);
entities.add(type);
}
}
public void setBasePackage(String basePackage) {
this.basePackages = new String[]{basePackage};
}
public void setBasePackages(String[] basePackages) {
this.basePackages = basePackages;
}
#Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
}
Here's how it's configured:
<b:bean id="sessionFactory" class="com.mycompany.spring.ExtendedAnnotationSessionFactoryBean">
<b:property name="dataSource" ref="dataSource" />
<b:property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
<b:property name="hibernateProperties" ref="hibernateProperties" />
<b:property name="entityInterceptor" ref="baseEntityInterceptor" />
<b:property name="basePackages">
<b:list>
<b:value>com.mycompany.entities</b:value>
<b:value>com.mycompany.entities1_1</b:value>
</b:list>
</b:property>
</b:bean>
The source code in each package (com.mycompany.entities, com.mycompany.entities1_1) is identical except that the catalog is defined in the second one:
#Table(catalog="myDatabase1_1", name = "mytablename1")
When I run a test I get a crash with a stack trace which states that the same entity name is being used twice (although they are in different packages). At the end of the stack trace, it suggests setting the "auto-import" to false:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyTableName1 refers to both com.mycompany.entities1_1.MyTableName1 and com.mycompany.entities.MyTableName1 (try using auto-import="false")
Questions: What auto-import mean, why would it work, and where would I specify it?
Here's the entire stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [file:WEB-INF/myconfiguration.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of the same entity name twice: MyTableName1
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [file:WEB-INF/myconfiguration.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of the same entity name twice: MyTablenNme1
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.nuval.infrastructure.test.BaseTest.init(BaseTest.java:44)
at com.nuval.infrastructure.test.BaseTest.setUp(BaseTest.java:62)
at com.nuval.test.CloneTest.setUp(CloneTest.java:104)
at junit.framework.TestCase.runBare(TestCase.java:125)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.AnnotationException: Use of the same entity name twice: MyTableName1
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:347)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:613)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:636)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:359)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:673)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at com.zeer.onqi.spring.ExtendedAnnotationSessionFactoryBean.afterPropertiesSet(ExtendedAnnotationSessionFactoryBean.java:36)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
... 30 more
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyTableName1 refers to both com.mycompany.entities1_1.MyTableName1 and com.mycompany.entities.MyTableName1 (try using auto-import="false")
at org.hibernate.cfg.Configuration$MappingsImpl.addImport(Configuration.java:2418)
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:340)
... 39 more
Your problem is not related to your bean and is caused by the fact that you have two entities with the same logical name in your SessionFactory. It means that Hibernate won't be able to understand which entity should it use in query such as from MyTableName1.
If you really need to have these entities in the same SessionFactory simultaneously, you should specify different logical names for them, as follows:
#Entity(name = "MyTableName1")
#Table(...)
public class MyTableName1 { ... }
#Entity(name = "MyTableName1_1")
#Table(...)
public class MyTableName1 { ... }
and use these names in HQL queries.
If you don't need them simultaneously, perhaps you can put them into different SessionFactories for different schemas.
Also note that, as far as I understand, you don't need to create your own subclass of AnnotationSessionFactoryBean, because the default one supports the same functionality as you try to achieve, see packagesToScan property.

Unit Testing Struts2 + Spring action with DAO

I'm trying to unit test struts2 actions (hitting a real database), but I haven't been able to connect to the db successfully.
I'm new to Spring, and the project setup uses jdbctemplate in multiple beans and DAO classes.
Here's my attempt so far:
Test Class:
public class Test extends StrutsSpringTestCase {
private static final String serverURL = "jdbc:db2://xxxx.xxx.com:----/xxxx";
private static final String username = "xxxxxxx";
private static final String password = "xxxxxxx";
#Override
public String[] getContextLocations() {
SimpleNamingContextBuilder s = new SimpleNamingContextBuilder();
DB2SimpleDataSource db=new DB2SimpleDataSource();
try {
DriverManager.registerDriver( new com.ibm.db2.jcc.DB2Driver() );
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
Class.forName("com.ibm.db2.jcc.DB2DataSource");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
db.setServerName(serverURL);
db.setPortNumber(----);
db.setUser(username);
db.setPassword(password);
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.websphere.naming.WsnInitialContextFactory");
env.put(Context.PROVIDER_URL, "iiop://xxxx.xxx.com:----");
Context ctx = new InitialContext(env);
Context javaCtx = ctx.createSubcontext("jdbc");
javaCtx.bind("xxx", db);
ctx.bind("java:", javaCtx);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
String[] locations = new String[1];
locations[0] = "xxxx.xml";
return locations;
}
public void test() throws Exception {
ActionProxy proxy = getActionProxy("/test");
testAction rd = (testAction) proxy.getAction();
System.out.println(rd.testMethod());
}
}
ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean name="jndi" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/XXX" />
</bean>
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver"/>
<property name="url" value="jdbc:db2://----.---.com:xxxx/xxxx"/>
<property name="username" value="xxxxxxxx"/>
<property name="password" value="xxxxxxxx"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean>
<bean id="xxxxDao"
class="xxxx">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
(continues on with other DAO-related beans).
Many classes rely on JdbcTemplate, as seen below, so I'd like to find a solution that includes it:
private JdbcTemplate jdbcTemplate;
private String schemaName = "xxxxxx";
private String procedureName = "xxxxxx";
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public RDResponseBO browseRD(RDRequestBO rdReqBO) {
SimpleJdbcCall storedProc = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schemaName)
.withoutProcedureColumnMetaDataAccess().withProcedureName(
procedureName); .........
My applicationContext.xml includes a datasource and a jndi bean, which is a little redundant. I don't know if it's possible to combine them both in JdbcTemplate in order to have the connection succeed.
Using the datasource alone results in a missing metadata/jdbc exception...and while i'd like to use the jndiobjectfactorybean class, the bean does not initialize in JUnit without running it through the server.
I tried including the jndi bean (after calling simplenamingcontextbuilder) in the jdbctemplate bean, which resulted in a matching constructor exception.
Ideas/Suggestions?
P.S. I apologize if the question format is a little off, I'm new to stackoverflow as well.
Stacktrace for jndi bean error:
.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTemplate' defined in class path resource [beans.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.apache.struts2.StrutsSpringTestCase.setupBeforeInitDispatcher(StrutsSpringTestCase.java:39)
at org.apache.struts2.StrutsTestCase.setUp(StrutsTestCase.java:187)
at junit.framework.TestCase.runBare(TestCase.java:128)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
JNDI error before using SimpleNamingContextBuilder:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jndi' defined in class path resource [beans.xml]: Invocation of init method failed; nested exception is com.ibm.websphere.naming.CannotInstantiateObjectException: Exception occurred while the JNDI NamingManager was processing a javax.naming.Reference object. [Root exception is java.lang.NoClassDefFoundError: com.ibm.wsspi.runtime.service.WsServiceRegistry]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.apache.struts2.StrutsSpringTestCase.setupBeforeInitDispatcher(StrutsSpringTestCase.java:39)
at org.apache.struts2.StrutsTestCase.setUp(StrutsTestCase.java:187)
at junit.framework.TestCase.runBare(TestCase.java:128)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: com.ibm.websphere.naming.CannotInstantiateObjectException: Exception occurred while the JNDI NamingManager was processing a javax.naming.Reference object. [Root exception is java.lang.NoClassDefFoundError: com.ibm.wsspi.runtime.service.WsServiceRegistry]
at com.ibm.ws.naming.util.Helpers.processSerializedObjectForLookupExt(Helpers.java:1033)
at com.ibm.ws.naming.util.Helpers.processSerializedObjectForLookup(Helpers.java:730)
at com.ibm.ws.naming.jndicos.CNContextImpl.processResolveResults(CNContextImpl.java:3691)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1861)
at com.ibm.ws.naming.jndicos.CNContextImpl.doLookup(CNContextImpl.java:1762)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookupExt(CNContextImpl.java:1513)
at com.ibm.ws.naming.jndicos.CNContextImpl.lookup(CNContextImpl.java:645)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:166)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:180)
at javax.naming.InitialContext.lookup(InitialContext.java:455)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 25 more
Caused by: java.lang.NoClassDefFoundError: com.ibm.wsspi.runtime.service.WsServiceRegistry
at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl$2.run(WSManagedConnectionFactoryImpl.java:835)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl.<init>(WSManagedConnectionFactoryImpl.java:840)
at java.lang.J9VMInternals.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1325)
at com.ibm.ejs.j2c.ConnectionFactoryBuilderImpl.createMCF(ConnectionFactoryBuilderImpl.java:1491)
at com.ibm.ejs.j2c.ConnectionFactoryBuilderImpl.processObjectInstance(ConnectionFactoryBuilderImpl.java:746)
at com.ibm.ejs.j2c.ConnectionFactoryBuilderImpl.processObjectInstance(ConnectionFactoryBuilderImpl.java:705)
at com.ibm.ejs.j2c.ConnectionFactoryBuilderImpl.getObjectInstance(ConnectionFactoryBuilderImpl.java:664)
at javax.naming.spi.NamingManager.getObjectInstanceByFactoryInReference(NamingManager.java:485)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:350)
at com.ibm.ws.naming.util.Helpers.processSerializedObjectForLookupExt(Helpers.java:927)
... 44 more
Caused by: java.lang.ClassNotFoundException: com.ibm.wsspi.runtime.service.WsServiceRegistry
at java.lang.ClassNotFoundException.<init>(ClassNotFoundException.java:77)
at java.net.URLClassLoader.findClass(URLClassLoader.java:383)
at java.lang.ClassLoader.loadClass(ClassLoader.java:652)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:346)
at java.lang.ClassLoader.loadClass(ClassLoader.java:618)
... 56 more
javax.naming.CommunicationException: A communication failure occurred while attempting to obtain an initial context with the provider URL: "iiop://xxxx.xxx.com:----". Make sure that any bootstrap address information in the URL is correct and that the target name server is running. A bootstrap address with no port specification defaults to port 2809. Possible causes other than an incorrect bootstrap address or unavailable name server include the network environment and workstation network configuration. [Root exception is org.omg.CORBA.COMM_FAILURE: purge_calls:1988 Reason: CONN_ABORT (1), State: ABORT (5) vmcid: IBM minor code: 306 completed: Maybe]
at com.ibm.ws.naming.util.WsnInitCtxFactory.mapInitialReferenceFailure(WsnInitCtxFactory.java:2269)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getWsnNameService(WsnInitCtxFactory.java:1457)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootContextFromServer(WsnInitCtxFactory.java:987)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getRootJndiContext(WsnInitCtxFactory.java:909)
at com.ibm.ws.naming.util.WsnInitCtxFactory.getInitialContextInternal(WsnInitCtxFactory.java:581)
at com.ibm.ws.naming.util.WsnInitCtx.getContext(WsnInitCtx.java:124)
at com.ibm.ws.naming.util.WsnInitCtx.getContextIfNull(WsnInitCtx.java:799)
at com.ibm.ws.naming.util.WsnInitCtx.createSubcontext(WsnInitCtx.java:370)
at com.ibm.ws.naming.util.WsnInitCtx.createSubcontext(WsnInitCtx.java:385)
at javax.naming.InitialContext.createSubcontext(InitialContext.java:523)
at junit.Test.getContextLocations(Test.java:88)
at org.apache.struts2.StrutsSpringTestCase.setupBeforeInitDispatcher(StrutsSpringTestCase.java:39)
at org.apache.struts2.StrutsTestCase.setUp(StrutsTestCase.java:187)
at junit.framework.TestCase.runBare(TestCase.java:132)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: org.omg.CORBA.COMM_FAILURE: purge_calls:1988 Reason: CONN_ABORT (1), State: ABORT (5) vmcid: IBM minor code: 306 completed: Maybe
at com.ibm.rmi.iiop.Connection.purge_calls(Connection.java:1987)
at com.ibm.rmi.iiop.Connection.doReaderWorkOnce(Connection.java:3134)
at com.ibm.rmi.transport.ReaderThread.run(ReaderPoolImpl.java:138)
Replace your been with this
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>

Resources