Spring 3.1 Java based configuration -- IllegalStateException - spring

I am working my way through a Spring tutorial, I have the following code, using Java based configuration, that isn't working. In my classpath I have the Spring 3.1 jars, as well as asm-4.0.jar and cglib-2.2.2.jar.
MainApp.java:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(
HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}
HelloWorldConfig.java:
package com.tutorialspoint;
import org.springframework.context.annotation.*;
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld() {
return new HelloWorld();
}
}
HelloWorld.java:
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
Error code:
Exception in thread "main" java.lang.IllegalStateException: Cannot load configuration class: com.tutorialspoint.HelloWorldConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:456)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigurationClasses(ConfigurationClassPostProcessor.java:202)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:176)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:604)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:437)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:68)
at com.tutorialspoint.MainApp.main(MainApp.java:8)
Caused by: java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at net.sf.cglib.core.AbstractClassGenerator.<init>(AbstractClassGenerator.java:38)
at net.sf.cglib.core.KeyFactory$Generator.<init>(KeyFactory.java:127)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:112)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer(ConfigurationClassEnhancer.java:101)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:89)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:448)
... 6 more

I changed the asm jar file from asm-4.0.jar to asm-3.3.jar, and it worked. There must have been a conflict between the first asm jar and the cglib jar I was using.

I was using cglib-2.1_3.jar and asm 3.1.jar when I ran in to this problem for the first time. After I removed the asm 3.1.jar and added asm- 1.5.3.jar it started working.

I was use cglib-2.1_3.jar and asm- 1.5.3, after using this jar my program run successfully.
ASM Core ยป 1.5.3
cglib-2.1_3.jar

Just adding this answer in case someone runs into the weird corner case issue I experienced.
This can also happen when the Jar file isn't properly signed.

Related

How to read external xml in spring boot 2.1.7 using external path as command line argument or config folder

Am working on a spring boot application having external configuration.Jar file run via command prompt using following command.
java -jar Service-1.0.jar --spring.config.additional-location=C:/Users/Administrator/Desktop/Springboot/
Need to pass external configuration path via command line argument,because they may varying.
Main class
#ImportResource(locations = {
"config/spring/service-config.xml",
"config/spring/datasource-config.xml"
})
public class ServiceMain {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ServiceMain.class)
.build()
.run(args);
for (String name : applicationContext.getBeanDefinitionNames()) {
}
}
}
when i run this jar it showing the following error
EDIT 1
changed running command
java -jar Service-1.0.jar --spring.config.additional-location=C:/Users/Administrator/Desktop/Springboot/,--external.config=C:/Users/Administrator/Desktop/Springboot/
changed main class
#ImportResource(locations = {
"${external.config}/config/spring/service-config.xml",
"${external.config}/config/spring/datasource-config.xml"
})
public class ServiceMain {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(ServiceMain.class)
.build()
.run(args);
for (String name : applicationContext.getBeanDefinitionNames()) {
}
}
}
it showing exception
java.lang.IllegalArgumentException: Could not resolve placeholder 'external.config' in value "${external.config}/config/spring/service-config.xml"
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:315)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at com.ge.hcit.xer.app.services.api.XERServiceMain.main(XERServiceMain.java:31)
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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'external.config' in value "${external.config}/config/spring/service-config.xml"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211)
at org.springframework.core.env.AbstractEnvironment.resolveRequiredPlaceholders(AbstractEnvironment.java:575)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:311)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
... 18 common frames omitted
how the importresource taking the external configuration
EDIT 2
Am placing configuration in config folder.external application.properties are loading in current project,but its not loading in dependency project.
#Configuration
public class ConfigurationFactory
{
public static final String REQ_CONF = "config/Configuration.xml";
public static final String FILTER_XML_CONF = "config/DocFilter.xml";
}
Is the spring load external application.properties/yml files only?
Use the file: prefix for system resource file:
#ImportResource(locations = {
"file:${external.config.location}/config/spring/service-config.xml",
"file:${external.config.location}/config/spring/datasource-config.xml"
})
Run with --external.config.location=xxx:
java -jar Service-1.0.jar --external.config.location=C:/Users/Administrator/Desktop/Springboot
Nothing wrong with your approach.
Instead of command line, add that as variable in application.properties file
please separate place holder and remaining path,
like ("${external.config}"+"/spring/service-config.xml")

spring boot and camel throws direct.DirectConsumerNotAvailableException

I'm trying to get simple example of springboot and camel working but come undone. Not sure what i'm doing wrong. in the gradle build i've included so far
dependencies {
compile 'org.apache.camel:camel-spring-boot-starter:2.18.4'
compile 'org.apache.camel:camel-groovy:2.18.4'
compile 'org.apache.camel:camel-stream:2.18.4'
compile 'org.codehaus.groovy:groovy-all:2.4.11'
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
i've create a DirectRoute component like this
#Component
class DirectRoute extends RouteBuilder{
#Override
void configure () throws Exception {
from ("direct:in") //tried stream:in also
.to ("stream:out")
}
}
I then have a driver bean that try's to invoke the route
#Component
public class HelloImpl implements Hello {
#Produce(uri = "direct:in")
private ProducerTemplate template;
#Override
public String say(String value) throws ExecutionException, InterruptedException {
assert template
println "def endpoint is : " + template.getDefaultEndpoint()
return template.sendBody (template.getDefaultEndpoint(), value)
}
}
lastly in the springboot application class i added a command line runner like this, that gets my bean from the spring context, and invokes the say method. I'm using groovy so i just passed a closure to the command line runner.
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//return closure to run on startup - just list the beans enabled
{args ->
println("Let's inspect the beans provided by Spring Boot:")
String[] beanNames = ctx.getBeanDefinitionNames()
Arrays.sort(beanNames)
for (String beanName : beanNames) {
println(beanName)
}
println("call the direct:start route via the service")
Hello service = ctx.getBean("helloService")
def result = service.say("William")
println "service returned : $result "
}
}
when i run my application i get all the bean names printed out (that's ok), however when i invoke the direct:in via producer template i get this error (org.apache.camel.component.direct.DirectConsumerNotAvailableException) see below.
I was expecting the route to be triggered the name sent to see that arrive in the output stream - but this is what i get.
Caused by: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-MONSTER-PC2-58911-1496920205300-0-2]
at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1795) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.util.ExchangeHelper.extractResultBody(ExchangeHelper.java:677) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:515) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:511) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:163) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.ProducerTemplate$sendBody$0.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) [groovy-all-2.4.11.jar:2.4.11]
at services.HelloImpl.say(HelloImpl.groovy:29) ~[main/:na]
at services.Hello$say.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) [groovy-all-2.4.11.jar:2.4.11]
at application.Application$_commandLineRunner_closure1.doCall(Application.groovy:47) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.Closure.call(Closure.java:414) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:54) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:124) ~[groovy-all-2.4.11.jar:2.4.11]
at com.sun.proxy.$Proxy44.run(Unknown Source) ~[na:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
... 10 common frames omitted
Caused by: org.apache.camel.component.direct.DirectConsumerNotAvailableException: No consumers available on endpoint: direct://in. Exchange[ID-MONSTER-PC2-58911-1496920205300-0-2]
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:55) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:529) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:497) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:365) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:497) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:225) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:144) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:161) ~[camel-core-2.18.4.jar:2.18.4]
What have i done wrong - and why does the producer template invocation on 'direct:in' (also tried stream in with same problem) not work? I thought that .to("stream:out") would be a consumer.
any pointers or advice gratefully received at this point
I have an update on my problems:
I had a subpackage with the application class annotated with #SpringBootApplication. So yes, unadorned it only scans subpackages.
you can add scanBasePackages= or scanBaseClasses= parameter, however when I tried doing a scan for single class, it seemed to scan the whole directory any way and grabbed the others as well.
I refactored the app to have a single root package with subpackages and elected to set the 'scanBasePakages to the new root package. but left the Application class in its own subpackage (personal preference only - documentation suggests leaving the Application in the root package)
you can now add other classes annotated with #Configuration to generate beans or use the basic #Component.
if you create Camel routes annotated with #Component they will be auto configured in the camelContext for you.
it appears by default that Spring isnt not starting the camelContext for you. When I checked the status of the context it shows as starting and not started. so in my commandLineRunner I had to start get the spring injected camelContext and had to start it myself, and exited it when I finished. I was slightly suprised as I thought SpringBootStarter would auto start the camelContext, but it appears not.
once you have Spring component scanning etc working and you start the camelContext, then problems with the org.apache.camel.component.direct.DirectConsumerNotAvailableException exception went away and things started to work - at least the baby examples I'm trying.
So revised structure now looks like this:
The revised ApplicationClass now looks like this with some simple println output to see the state of the context, and beans in the spring ctx. The helleoService bean is still the proxy I use to setup the producer template to call the DirectRoute.
package com.softwood.application
import groovy.util.logging.Slf4j
import org.apache.camel.CamelContext
import org.springframework.beans.factory.annotation.Autowired
import com.softwood.services.Hello
/**
* Created by willw on 07/06/2017.
*/
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean
#Slf4j //inject logger
#SpringBootApplication (scanBasePackages = ["com.softwood"]) //forces scan at parent
// same as #Configuration #EnableAutoConfiguration #ComponentScan with 'defaults' e.g. sub packages
public class Application {
#Autowired
ApplicationContext ctx
#Autowired
CamelContext camelContext
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//return closure to run on startup - just list the beans enabled
{args ->
println("Let's inspect the beans provided by Spring Boot:")
String[] beanNames = ctx.getBeanDefinitionNames()
Arrays.sort(beanNames)
for (String beanName : beanNames) {
println(beanName)
}
/* when component scan is working - bean routes are added
automatically to camel context via springBoot, however you do have to start
the camel context, yourself
*/
println "camelCtx has following components : " + camelContext.componentNames
println "camelCtx state is : " + camelContext.status
println "starting camel context"
camelContext.start()
println "camelCtx state now is : " + camelContext.status
//log.debug "wills logging call "
println("call the direct:start route via the service")
Hello service = ctx.getBean("helloService")
def result = service.say("William")
println "service returned : $result "
println "sleep 5 seconds "
sleep (5000)
println "stop camel context"
camelContext.stop()
println "camelCtx state now is : " + camelContext.status
}
}
}
That proxy is just registered as a simple bean like this in the spring context
package com.softwood.services
/**
* Created by willw on 07/06/2017.
*/
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutionException
#Component
public class HelloImpl implements Hello {
#Produce(uri = "direct:in") /* ?block=true */
private ProducerTemplate template
#Override
public String say(String value) throws ExecutionException, InterruptedException {
assert template
println "def endpoint is : " + template.getDefaultEndpoint()
//Future future = template.asyncSendBody(template.getDefaultEndpoint(), value)
//return future.get()
return template.sendBody (template.getDefaultEndpoint(), value)
}
}
The TimedRoute just sorts itself out with no template required to invoke in
package com.softwood.camelRoutes
/**
* Created by willw on 07/06/2017.
*/
import org.apache.camel.builder.RouteBuilder
import org.springframework.stereotype.Component
#Component
class TimedRoute extends RouteBuilder {
#Override
void configure () throws Exception {
from ("timer:foo")
.to ("log:com.softwood.application.Application?level=WARN")
}
}
My simple no-op file route isn't working (yet) and not sure why. I suspect I've not got the file config right somehow; some playing is required.
package com.softwood.camelRoutes
import org.apache.camel.builder.RouteBuilder
import org.springframework.stereotype.Component
/**
* Created by willw on 08/06/2017.
*/
#Component
class FileNoOpRoute extends RouteBuilder{
#Override
void configure () throws Exception {
from ("file:../com.softwood.file-inbox?recursive=true&noop=true&idempotent=true")
.to ("file:../com.softwood.file-outbox")
}
}
However the basics are not working and least camel is doing something whereas before I just had the exception and nothing.
I have found another question on Spring config highlighting some of the above also.

Why the cryptic MultipleFailureException error message with the SpringJUnit4ClassRunner.withAfterClasses method

Why is my spring test set up failing with the following not-so-useful error messages below? All suggestions are appreciated.
JUnit Output
java.lang.NoClassDefFoundError: org/junit/runners/model/MultipleFailureException
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses(SpringJUnit4ClassRunner.java:188)
at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run (SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more
Console Output
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#76959acc, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#57e603e6, org.springframework.test.context.support.DirtiesContextTestExecutionListener#3e0a1e1f]
Here is the target snippet
#Service
public class PipApps {
#Resource( name = "apps" )
private Properties apps;
#Autowired
private SitePreferenceHandler sitePreferenceHandler;
#Autowired
private PipsTable pipsTable;
private SitePreference sitePreference;
private Device device;
public PipApps( HttpServletRequest request, HttpServletResponse response ){
sitePreference = sitePreferenceHandler.handleSitePreference( request, response );
device = DeviceUtils.getRequiredCurrentDevice( request );
}
public Properties getApps(){
return apps;
}
public Device getDevice(){
return device;
}
public SitePreference getSitePreference(){
return sitePreference;
}
public DeviceRouteTable getPipsTable(){
return pipsTable;
}
}
And the test snippet
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration( locations={"src/test/resources/PipAppsTest-context.xml"} )
public class PipAppsTest {
#Mock
SitePreferenceHandler sitePreferenceHandler;
#Autowired
PipApps pipApps;
...
}
Update -- September 2015
Spring Framework 4.2.2 throws a more meaningful exception if JUnit 4.9 is not in the classpath. See SPR-13521 for details.
The following is an excerpt from the class-level Javadoc for SpringJUnit4ClassRunner:
NOTE: As of Spring Framework 4.1, this class requires JUnit 4.9 or higher.
The class in question, MultipleFailureException, was introduced in JUnit 4.9.
So that's why your test is failing with the ClassNotFoundException.
Upgrading to JUnit 4.9 (or preferably 4.12) will therefore solve your problem.
Regards,
Sam (author of the Spring TestContext Framework)

glassfish 4 EJB 3 standalone client jndi lookup

I have problem with calling remote ejb. I have successfully deployed remote EJB:
public interface IHelloWordlHome extends EJBHome {
mybeans.IHelloWordl create() throws RemoteException, javax.ejb.CreateException;
}
public interface IHelloWordl extends javax.ejb.EJBObject {
public String hello(String name) throws RemoteException;
}
#javax.ejb.Stateless(name = "HelloWordlEJB")
public class HelloWordlBean implements Serializable {
public HelloWordlBean() {
}
public String hello(String name) {
return "asd" + name;
}
public void ejbCreate() throws CreateException {
}
}
ejb-jar.xml:
<enterprise-beans>
<session>
<ejb-name>HelloWordlEJB</ejb-name>
<home>mybeans.IHelloWordlHome</home>
<remote>mybeans.IHelloWordl</remote>
<ejb-class>mybeans.HelloWordlBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
and now I am trying to run standalone client. That means it's totaly different application which now runs on same machine as server (localhost) but later it will run on different machine. As the glassfish description (dont have the link atm) says I used InitialContext without parameters, in server log I found the JNDI name of my bean ("java:global/ear_ear_exploded/ejb/HelloWordlEJB!mybeans.HelloWordlBean") and trying to look it up. I use gl-client.jar lib and I have it on my classpath. Note that I didnt copy that .jar, I am using the .jar in glassfish installation folder (I know that could be problem becouse it links other .jars) I copied (ctrl+c & ctrl+v) the bean interface (IHelloWordl) from server to client.
client code:
public static void main(String[] args) throws NamingException, RemoteException {
IHelloWordl foo = (IHelloWordl) new InitialContext().lookup("java:global/ear_ear_exploded/ejb/HelloWordlEJB!mybeans.HelloWordlBean");
foo.hello("Martin");
}
This is what my IDE runs:
P:\Java\jdk1.8.0\bin\java -Didea.launcher.port=7534 "-Didea.launcher.bin.path=P:\IntelliJ IDEA 13.1.1\bin" -Dfile.encoding=UTF-8 -classpath "P:\Java\jdk1.8.0\jre\lib\charsets.jar;P:\Java\jdk1.8.0\jre\lib\deploy.jar;P:\Java\jdk1.8.0\jre\lib\javaws.jar;P:\Java\jdk1.8.0\jre\lib\jce.jar;P:\Java\jdk1.8.0\jre\lib\jfr.jar;P:\Java\jdk1.8.0\jre\lib\jfxswt.jar;P:\Java\jdk1.8.0\jre\lib\jsse.jar;P:\Java\jdk1.8.0\jre\lib\management-agent.jar;P:\Java\jdk1.8.0\jre\lib\plugin.jar;P:\Java\jdk1.8.0\jre\lib\resources.jar;P:\Java\jdk1.8.0\jre\lib\rt.jar;P:\Java\jdk1.8.0\jre\lib\ext\access-bridge.jar;P:\Java\jdk1.8.0\jre\lib\ext\cldrdata.jar;P:\Java\jdk1.8.0\jre\lib\ext\dnsns.jar;P:\Java\jdk1.8.0\jre\lib\ext\jaccess.jar;P:\Java\jdk1.8.0\jre\lib\ext\jfxrt.jar;P:\Java\jdk1.8.0\jre\lib\ext\localedata.jar;P:\Java\jdk1.8.0\jre\lib\ext\nashorn.jar;P:\Java\jdk1.8.0\jre\lib\ext\sunec.jar;P:\Java\jdk1.8.0\jre\lib\ext\sunjce_provider.jar;P:\Java\jdk1.8.0\jre\lib\ext\sunmscapi.jar;P:\Java\jdk1.8.0\jre\lib\ext\sunpkcs11.jar;P:\Java\jdk1.8.0\jre\lib\ext\zipfs.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\out\production\project-ejbclient;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.annotation.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.ejb.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.jms.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.transaction.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.persistence.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.servlet.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.resource.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.servlet.jsp.jar;D:\projects\self\dt-reservation-system-for-doctors\project-ejbclient\lib\javax.servlet.jsp.jstl.jar;P:\glassfish4\glassfish\lib\gf-client.jar;P:\glassfish4\glassfish\lib\appserv-rt.jar;P:\IntelliJ IDEA 13.1.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain mybeans.Main
When I run the client I am getting exception which I can't realy understand and found no help online:
Exception in thread "main" javax.naming.CommunicationException: Communication exception for SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [Root exception is java.rmi.MarshalException: CORBA BAD_PARAM 1398079494 Maybe; nested exception is:
java.io.NotSerializableException: ----------BEGIN server-side stack trace----------
org.omg.CORBA.BAD_PARAM: WARNING: 00100006: Class mybeans.__EJB31_Generated__HelloWordlBean__Intf____Bean__ is not Serializable vmcid: SUN minor code: 6 completed: Maybe
at com.sun.proxy.$Proxy153.notSerializable(Unknown Source)
at com.sun.corba.ee.impl.misc.ORBUtility.throwNotSerializableForCorba(ORBUtility.java:783)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.writeAny(Util.java:360)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$10.write(DynamicMethodMarshallerImpl.java:306)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.writeResult(DynamicMethodMarshallerImpl.java:488)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:177)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
----------END server-side stack trace----------]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:513)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at mybeans.Main.main(Main.java:10)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.rmi.MarshalException: CORBA BAD_PARAM 1398079494 Maybe; nested exception is:
java.io.NotSerializableException: ----------BEGIN server-side stack trace----------
org.omg.CORBA.BAD_PARAM: WARNING: 00100006: Class mybeans.__EJB31_Generated__HelloWordlBean__Intf____Bean__ is not Serializable vmcid: SUN minor code: 6 completed: Maybe
at com.sun.proxy.$Proxy153.notSerializable(Unknown Source)
at com.sun.corba.ee.impl.misc.ORBUtility.throwNotSerializableForCorba(ORBUtility.java:783)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.writeAny(Util.java:360)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$10.write(DynamicMethodMarshallerImpl.java:306)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.writeResult(DynamicMethodMarshallerImpl.java:488)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:177)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
----------END server-side stack trace----------
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:300)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:211)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
at com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
at com.sun.enterprise.naming.impl._SerialContextProvider_DynamicStub.lookup(com/sun/enterprise/naming/impl/_SerialContextProvider_DynamicStub.java)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
... 8 more
Caused by: java.io.NotSerializableException: ----------BEGIN server-side stack trace----------
org.omg.CORBA.BAD_PARAM: WARNING: 00100006: Class mybeans.__EJB31_Generated__HelloWordlBean__Intf____Bean__ is not Serializable vmcid: SUN minor code: 6 completed: Maybe
at com.sun.proxy.$Proxy153.notSerializable(Unknown Source)
at com.sun.corba.ee.impl.misc.ORBUtility.throwNotSerializableForCorba(ORBUtility.java:783)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.writeAny(Util.java:360)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$10.write(DynamicMethodMarshallerImpl.java:306)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.writeResult(DynamicMethodMarshallerImpl.java:488)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:177)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
----------END server-side stack trace----------
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:292)
... 13 more
Caused by: org.omg.CORBA.BAD_PARAM: ----------BEGIN server-side stack trace----------
org.omg.CORBA.BAD_PARAM: WARNING: 00100006: Class mybeans.__EJB31_Generated__HelloWordlBean__Intf____Bean__ is not Serializable vmcid: SUN minor code: 6 completed: Maybe
at com.sun.proxy.$Proxy153.notSerializable(Unknown Source)
at com.sun.corba.ee.impl.misc.ORBUtility.throwNotSerializableForCorba(ORBUtility.java:783)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.writeAny(Util.java:360)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$10.write(DynamicMethodMarshallerImpl.java:306)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.writeResult(DynamicMethodMarshallerImpl.java:488)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:177)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
----------END server-side stack trace---------- vmcid: SUN minor code: 6 completed: Maybe
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase.getSystemException(MessageBase.java:813)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage_1_2.getSystemException(ReplyMessage_1_2.java:131)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.getSystemExceptionReply(MessageMediatorImpl.java:594)
at com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl.processResponse(ClientRequestDispatcherImpl.java:519)
at com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl.marshalingComplete(ClientRequestDispatcherImpl.java:393)
at com.sun.corba.ee.impl.protocol.ClientDelegateImpl.invoke(ClientDelegateImpl.java:272)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:198)
... 12 more
I am despread :/ Can anyone help?
I'm not sure where you got this from but it looks like you mixed something up. In EJB 3 you don't have to extend EJBHome or EJBObject. You don't need the HomeInterface.
You should do it in this way:
import javax.ejb.Remote;
#Remote
public interface HelloWorldRemote {
public String hello(String name);
}
and:
#javax.ejb.Stateless(name = "HelloWorldEJB")
public class HelloWorldBean implements HelloWorldRemote {
public String hello(String name) {
return "asd" + name;
}
}
PS: There was a typo in your HelloWorld (HelloWordl).
You don't need any declaration in the ejb-jar.xml.
The client-code should look similar to this:
InitialContext con = new InitialContext();
HelloWorldBean foo = (HelloWorldBean) con.lookup("java:global/ear_ear_exploded/HelloWorldEJB");
See also:
EJB creating using SessionBean EJBObject and EJBHome interfaces
How to make EJB3 remote interface available to client?
EJB - Home/Remote and LocalHome/Local interfaces
Your class must be serializable, meaning your EJB needs implements Serializable

Spring issue with profile

I am trying to get the variables uploaded directly based on environment in which the code is running. I wrote some code and ran into issues. Can you please point me what i am doing wrong.
WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.configs");
root.getEnvironment().setActiveProfiles("dev");
root.refresh();
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
ServletRegistration.Dynamic appServlet = sc.addServlet("appServlet",
new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException(
"'appServlet' could not be mapped to '/' due "
+ "to an existing mapping. This is a known issue under Tomcat versions "
+ "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
DynamicConfig.java
#Configuration
#Profile("dev")
#PropertySource("classpath:/devel.properties")
public class DynamicConfig {
#Autowired
Environment env;
#Bean
public TestClass testClass(){
TestClass testClass = new TestClass();
testClass.setEnvironment(env.getProperty("environment"));
return testClass;
}
}
TestClass is simple class with one instance variable which will come from config based on environment.
TestCase:
package com.tester;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.configs.DynamicConfig;
import com.configs.EnvironmentDetector;
import com.tester.TestClass;
public class TestClassTest {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DynamicConfig.class);
#Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(DynamicConfig.class);
context.getEnvironment().setActiveProfiles("dev");
context.scan("com.configs");
TestClass test = context.getBean(TestClass.class);
System.out.println(test.getEnvironment());
}
}
Now I am getting below error
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.282 sec <<< FAILURE!
test(com.tester.TestClassTest) Time elapsed: 0.279 sec <<< ERROR!
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.tester.TestClass] is defined: expected single bean but found 0:
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:280)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1106)
at com.tester.TestClassTest.test(TestClassTest.java:16)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:35)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:146)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:97)
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.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
at $Proxy0.invoke(Unknown Source)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:145)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:87)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)
When i remove the line #profile("dev") from the DynamicConfig.java code is running fine. But i want that. I want to create similar classes for prod.
Please help
Thanks
Update your test class to activate the profile. Currently you are activating it by adding the property in the WebApplicationInitializer which is not run in the context of your test.
One way to activate it would be doing the following, however it is not the only way:
#RunWith(SpringJUnit4ClassRunner.class)
#ActiveProfiles({"dev"})
#ContextConfiguration(classes = {DynamicConfig.class})
public class TestClassTest {
#Autowired
TestClass testClass;
#Test
public void test(){
System.out.println(testClass.getEnvironment());
}

Resources