Failed to load Spring ApplicationContext - spring

I'm writing unit tests for a spring application which is sort of complex. I want to load spring context in order to use defined beans. My context.xml is located at:
src/main/resources/context.xml
After maven build, the context.xml appears at:
target/classes/context.xml
In the pom.xml, I have: (As suggested by this post)
<resources>
<resource>
<filtering>true</filtering>
<directory>src/test/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<excludes>
<exclude>**/*local.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
I have tried to do this job in two ways:
1, Use ApplicationContext
AppliactionContext springContext = new ClassPathXmlApplicationContext("/context.xml");
MyObject myObject = springContext.getBean(myObject.class);
2, Use Annotations
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"/context.xml"})
public class myTest{
#Autowired
MyObject myObject;
...
}
But neither way works for me. Error message:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
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.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
... more
Important point: The context.xml was actually copied from another project. These projects run together as an application but when function as Junit, I don't know how to load the context from a different project so I simply copied and pasted the file. This might be a problem
More information
Failure Trace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'validator' defined in class path resource [context.xml]: BeanPostProcessor
before instantiation of bean failed; nested exception is
java.lang.NoClassDefFoundError: org.aspectj.lang.annotation.Aspect
Caused by: java.lang.NoClassDefFoundError: org.aspectj.lang.annotation.Aspect
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Aspect
So looks like I have to import some spring aop package first?
Please give suggestions. Much appreciation.

When running as junit test using Spring Test annotations, you need to use classpath in the locations like this
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:/context.xml")
And I don't use any resources definition in the pom.xml. You can remove that and try like this.

Related

How can I run JDK 19 with Structured Concurrency? (ERROR: java.lang.NoClassDefFoundError: jdk/incubator/concurrent/StructuredTaskScope)

Note: this post somehow related with this question; however, the error is different. So I am posting as another question.
I want to try the new Project Loom feature defined in: JEP 428: Structured Concurrency (Incubator)
I created a library project that uses class StructuredTaskScope, which can compile right.
Then I created a test project to demonstrate the use of library project, which can compile right too.
In pom.xml, both projects use:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<release>19</release>
<compilerArgs>
<arg>--enable-preview</arg>
<arg>--add-modules=jdk.incubator.concurrent</arg>
</compilerArgs>
</configuration>
</plugin>
However, When i try to run the test project, it returns error below:
C:\me\codes\com.tugalsan\tst\com.tugalsan.tst.thread>java -jar target/com.tugalsan.tst.thread-1.0-SNAPSHOT-jar-with-dependencies.jar --enable-preview --add-modules jdk.incubator.concurrent
Exception in thread "main" java.lang.NoClassDefFoundError: jdk/incubator/concurrent/StructuredTaskScope
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1013)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at com.tugalsan.api.thread.server.TS_ThreadFetchAll.<init>(TS_ThreadFetchAll.java:44)
at com.tugalsan.api.thread.server.TS_ThreadFetchAll.of(TS_ThreadFetchAll.java:85)
at com.tugalsan.tst.thread.Main.main(Main.java:13)
Caused by: java.lang.ClassNotFoundException: jdk.incubator.concurrent.StructuredTaskScope
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 12 more
I also tried adding '=' character, but no luck: java -jar target/com.tugalsan.tst.thread-1.0-SNAPSHOT-jar-with-dependencies.jar --enable-preview --add-modules=jdk.incubator.concurrent
As Joachim Sauer answered:
Everything after the -jar filename.jar will be passed as an argument.
Hence to run an app with jdk.incubator.concurrent, one should use below order:
java --enable-preview --add-modules jdk.incubator.concurrent -jar JARFILENAME.jar argument0 argument1 argument2...

Failed to load ApplicationContext from Unit Test: FileNotFound

I am creating a Maven Spring project, which includes MVC, Data and Security.
My Spring applicationContext-*.xml files are located at \src\main\resources\spring\
My TestCase is placed at \src\test\java\my\package\controller\ and its code is:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:spring/applicationContext.xml",
"classpath:spring/applicationContext-jpa.xml",
"classpath:spring/applicationContext-security.xml" })
public class MyControllerTest extends TestCase {
#Autowired
private MyController myController;
#Test
public void myMethod_test() {
}
}
When I right click on the test class and run as JUnit, I get
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at
[...]
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from class path resource
[applicationContext.xml]; nested exception is java.io.FileNotFoundException:
class path resource [applicationContext.xml] cannot be opened because it does not exist
[...]
If I try to remove applicationContext.xml from the locations, I still get exactly the same error. The complete stack trace is this:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
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:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
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: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.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:253)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:122)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
... 37 more
Try with the relative path using *
#ContextConfiguration(locations = {
"classpath*:spring/applicationContext.xml",
"classpath*:spring/applicationContext-jpa.xml",
"classpath*:spring/applicationContext-security.xml" })
If not look if your xml are really on resources/spring/.
Finally try just on without location
#ContextConfiguration({"classpath*:spring/applicationContext.xml"})
The other error that you´re showing is because you have this tag duplicated on applicationContext.xml and applicationContext-security.xml
Duplicate <global-method-security>
I added the spring folder to the build path and, after clean&build, it worked.
try as below
#ContextConfiguration (locations = "classpath*:/spring/applicationContext*.xml")
this will load all 3 of your application context xml file.
If you are using intellij, then try restarting intellij cache
File-> Invalidate cache/restart
clean and build project
See if it works, it worked for me.
For me, I was missing #ActiveProfile at my test class
#ActiveProfiles("sandbox")
class MyTestClass...
Give the below
#ContextConfiguration(locations = {"classpath*:/spring/test-context.xml"})
And in pom.xml give the following plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
Add in in pom.xml give the following plugin:
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<useFile>false</useFile>
</configuration>
</plugin>
I had the same problem and none of the previous answers have solved the issue for me.
I was getting the error due to the coexistence of spring-boot-starter-webflux and spring-boot-starter-tomcat in my pom.xml.
Excluding spring-boot-starter-tomcat from Test phase have solved the issue.
I used maven-surefire-plugin to do so :
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<classpathDependencyExcludes>
<classpathDependencyExclude>org.springframework.boot:spring-boot-starter-tomcat</classpathDependencyExclude>
</classpathDependencyExcludes>
</configuration>
</plugin>
</plugins>
</build>
spring-boot-starter-parent version : 2.6.3
I faced the same error and realized that pom.xml had java 1.7 and STS compiler pointed to Java 1.8. Upon changing compiler to 1.7 and rebuild fixed the issue.
PS: This answer is not related to actual question posted but applies to similar error for app Context not loading
Check your run debug configuration. This value must be your main Spring Boot Aplication class
if different class you can YourMainAplication.java --> Right Click --> Run
Thats it!
The problem is insufficient memory to load context.
Try to set VM options:
-da -Xmx2048m -Xms1024m -XX:MaxPermSize=2048m

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/util/Tool

I get below error when i package (jar) and run my defaulthadoopjob.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/util/Tool
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.util.Tool
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 12 more
Could not find the main class: DefaultHadoopJobDriver. Program will exit.
Commands used to build Jar.
# jar -cvf dhj.jar
# hadoop -jar dhj.jar DefaultHadoopJobDriver
The above command gave me error "Failed to load Main-Class manifest attribute from dhj.jar"
rebuilt jar with manifest using below command
jar -cvfe dhj.jar DefaultHadoopJobDriver .
hadoop -jar dhj.jar DefaultHadoopJobDriver -- This returned the original error message that I reported above.
My Hadoop job has single class "DefaultHoopJobDrive" that extends Configures and implements Tool, and run method as only code for Job creation and inputpath,outpurpath set.
Aslo I.m using new API.
I'm running hadoop 1.2.1 and the Job works fine from eclipse.
This might be something to do with the classpath. Please help.
For executing that jar you don't have to give hadoop -jar. The command is like so:
hadoop jar <jar> [mainClass] args...
If this jar again gets the java.lang.ClassNotFoundException exception then can you use the:
hadoop classpath
command to see whether hadoop-core-1.2.1.jar is present in your hadoop installations classpath?
FYI, and if it's not present in this list you have to add this jar to the hadoop lib directory.
Try building your hadoop java code with all hadoop jars available in hadoop's lib folder.
In this case you are missing the hadoop util class which is present in the hadoop-core-*.jar
Classpath can be specified while building the code within the jar or you can externalise it using the following command
hadoop -cp <path_containing_hadoop_jars> -jar <jar_name>
In case anyone is using Maven and lands here: Dependency issues can be resolved by asking Maven to include any jars it requires within the parent project's jar itself. That way, Hadoop doesn't have to look elsewhere for dependencies -- it can find them right there itself. Here's how to do this:
1. Go to pom.xml
Add a section to your <project> tag, called <build>
Add the following to your <build></build> section:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.7.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>org.slf4j:slf4j-api</exclude>
<exclude>junit:junit</exclude>
<exclude>jmock:jmock</exclude>
<exclude>xml-apis:xml-apis</exclude>
<exclude>org.testng:testng</exclude>
<exclude>org.mortbay.jetty:jetty</exclude>
<exclude>org.mortbay.jetty:jetty-util</exclude>
<exclude>org.mortbay.jetty:servlet-api-2.5</exclude>
<exclude>tomcat:jasper-runtime</exclude>
<exclude>tomcat:jasper-compiler</exclude>
<exclude>org.apache.hadoop:hadoop-core</exclude>
<exclude>org.apache.mahout:mahout-math</exclude>
<exclude>commons-logging:commons-logging</exclude>
<exclude>org.mortbay.jetty:jsp-api-2.1</exclude>
<exclude>org.mortbay.jetty:jsp-2.1</exclude>
<exclude>org.eclipse.jdt:core</exclude>
<exclude>ant:ant</exclude>
<exclude>org.apache.hadoop:avro</exclude>
<exclude>jline:jline</exclude>
<exclude>log4j:log4j</exclude>
<exclude>org.yaml:snakeyaml</exclude>
<exclude>javax.ws.rs:jsr311-api</exclude>
<exclude>org.slf4j:jcl-over-slf4j</exclude>
<exclude>javax.servlet:servlet-api</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/jruby.home</exclude>
<exclude>META-INF/license</exclude>
<exclude>META-INF/maven</exclude>
<exclude>META-INF/services</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
Now build your project again, and run with the normal hadoop java my.jar ... command. It shouldn't cry about dependencies now. Hope this helps!

Spring Security - Global Method Security using point-cut is not working

I want to apply method level security in my web app so that only authorized users can access those service layer methods.
There are two ways to implement this.
1) To annotate my service layer methods with #Secured annotation and in the dispatcher-servlet.xml file with configuration (<security:global-method-security secured-annotations="enabled" />).
But this would take a lot of time in my case as there are so many service class and methods already created so finding the methods and annotate them will not be a good way.
2) To define a point cut expression for methods level security that will automatically detect the methods having my custom annotation #SecuredAdmin in my services and secure them with the role ROLE_ADMIN.
In my case the option 1) is working very fine when I tried to test. And there is no issue. But when I tried the option 2) with following configuration I am not able to start my application.
<security:global-method-security>
<security:protect-pointcut access="ROLE_ADMIN" expression="execution(#com.xxx.yyy.zzz.services.SecuredAdmin * *.*(..))"/>
</security:global-method-security>
I am getting following exception when I tried to start my server.
java.lang.IllegalArgumentException: error annotation type patterns are only supported at Java 5 compliance level or above
org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:302)
org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:279)
org.springframework.security.config.method.ProtectPointcutPostProcessor.postProcessBeforeInitialization(ProtectPointcutPostProcessor.java:94)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1448)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:773)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
org.apache.catalina.ha.tcp.ReplicationValve.invoke(ReplicationValve.java:333)
org.apache.catalina.ha.session.JvmRouteBinderValve.invoke(JvmRouteBinderValve.java:219)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
I have tried every possible way to change the code compliance level to 1.6 in both pom files and eclipse project properties.
I am using Spring-Security 3.0 and aspectj related libraries are as following.
spring-aop-3.1.0.RELEASE.jar
spring-aspects-3.1.0.RELEASE.jar
aspectjrt-1.6.5.jar
aspectjweaver-1.6.5.jar
Please help me in this regards. Ask me if you require any further information.
Thanks in advance.
You have to configure aspect weaver to use java 1.6 compliance level. Add something like that to your pom.xml in build plugins section.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
</plugin>
I came across this problem with an older project - when I switched from jdk6 to jdk7, when the application started I encountered:
'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource'
while setting bean property 'transactionAttributeSource';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0':
Initialization of bean failed; nested exception is java.lang.IllegalArgumentException:
error annotation type patterns are only supported at Java 5 compliance level or above
I didn't want a purely maven solution because during development I run the app in Tomcat via the IDE (Intellij IDEA).
In the end I just upgraded my aspectjweaver dependency to 1.7.2 (it was 1.5.4)
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
Everything seems okay now.

Spring's LoadTimeWeaver Agent not starting up

I'm attempting to implement Load time weaving using Spring and AspectJ. To the best of my knowledge I have everything configured properly but I keep getting the error when I try to run my integration tests:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.weaving.AspectJWeavingEnabler#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver': Initialization of bean failed; nested exception is java.lang.IllegalStateException: ClassLoader [sun.misc.Launcher$AppClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
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:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:643)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.boku.risk.service.perisistence.PersistenceTestBase.setupBase(PersistenceTestBase.java:23)
at com.boku.risk.service.dao.CountryLimitDaoTest.setup(CountryLimitDaoTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver': Initialization of bean failed; nested exception is java.lang.IllegalStateException: ClassLoader [sun.misc.Launcher$AppClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
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:194)
at org.springframework.context.weaving.LoadTimeWeaverAwareProcessor.postProcessBeforeInitialization(LoadTimeWeaverAwareProcessor.java:95)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 37 more
Caused by: java.lang.IllegalStateException: ClassLoader [sun.misc.Launcher$AppClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
at org.springframework.context.weaving.DefaultContextLoadTimeWeaver.setBeanClassLoader(DefaultContextLoadTimeWeaver.java:83)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1436)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 46 more
My application context contains:
<context:load-time-weaver/>
And my pom contains:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-agent</artifactId>
<version>2.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.10</version>
</dependency>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>always</forkMode>
<argLine>
-javaagent:${settings.localRepository}/org/springframework/spring-agent/2.5.6/spring-agent-2.5.6.jar
</argLine>
</configuration>
</plugin>
</plugins>
</build>
It appears as if it can't figure out to load the spring-agent but I can't seem to figure out the reason for this. Thanks in advance for your help.
Try declaring an InstrumentationLoadTimeWeaver bean instead of explicitly using -javaagent:/path/to/org.springframework.instrument-{version}.jar. As per the documentation
To use it, you must start the virtual machine with the Spring agent, by supplying the following JVM options:
-javaagent:/path/to/org.springframework.instrument-{version}.jar
Note that this requires modification of the VM launch script which may prevent you from using this in application server environments (depending on your operation policies). Additionally, the JDK agent will instrument the entire VM which can prove expensive.
I am hoping doing the way below - here explained - would be better I guess.
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
The same can be done in xml configuration.
Found a new library that just solves to dynamically setup spring InstrumentationLoadTimeWeaver to enable support for aspects without having to start the JVM with an explicit java agent
<dependencies>
<dependency>
<groupId>de.invesdwin</groupId>
<artifactId>invesdwin-instrument</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>invesdwin</id>
<url>https://invesdwin.de/artifactory/invesdwin-oss-remote</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
Spring boot config
#SpringBootApplication
/**
* Make #Configurable work via #EnableLoadTimeWeaving.
* If it does not work, alternatively you can try:
* #ImportResource(locations = "classpath:/META-INF/ctx.spring.weaving.xml")
*/
#EnableLoadTimeWeaving
public class MySpringBootApplication {
public static void main(final String[] args) {
DynamicInstrumentationLoader.waitForInitialized(); //dynamically attach java agent to jvm if not already present
DynamicInstrumentationLoader.initLoadTimeWeavingContext(); //weave all classes before they are loaded as beans
SpringApplication.run(MySpringBootApplication.class, args); //start application, load some classes
}
}
Add this to your VM arguments in STS or eclipse
-javaagent:C:\\spring-instrument.jar
You could try and switch to the following agent:
-javaagent:C:\Users\YourName\.m2\repository\org\aspectj\aspectjweaver\1.6.10.RC1\aspectjweaver-1.6.10.RC1.jar
adding the jar file to the VM Arg's in the Launch Configuration did the trick for me as the previous poster stated. in STS 3.6.3, Run -> Run Configurations -> MyTcServerEntry -> Arguments tab then add in the jar. my example was: -javaagent:"D:\sts-3.6.3\sts-bundle\tcServer-2.6.5\myApp\lib\spring-instrument-3.0.5.RELEASE.jar"
If you are using Tomcat try adding the following in the catalina.bash for windows or catalina.sh for linux servers:
set CATALINA_OPTS=%CATALINA_OPTS% -javaagent:"C:\path\to\spring-instrument-3.1.1.RELEASE.jar"
Keep in mind it will work only in Tomcat versions less than 7.0.55. After that it wont take it. And you will need to add it in the context.xml as mentioned here load-time-weaver (aspectj-weaver) is not working in apache tomcat 7.0.55.

Resources