AspectJ + Perf4J + Spring and #Profiled annotation? - spring

I can't get AspectJ to work at all, and I have ran out of ideas after following 10 different tutorials.
Here is what I am trying to do...
I have a Spring application. It uses Spring, Perf4J, and Now Aspect(if it ever works!) and I want to use #Profiled("some tag here") at the tog of my public method. That is it, nothing too fancy.
Here is the code I am trying to run :
#Override
#Profiled(tag = "MainClass" + ".runMethod", logFailuresSeparately = true)
public Collection<Throwable> runMethod() throws Exception {
System.out.println("Running a simple method that I want timings for.");
}
Here are my POM dependencies used in maven to get everything to set up.
<dependencies>
<!-- Spring (includes spring-aop)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ (required spring-aop dependency) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<!-- LOG -->
<dependency>
<groupId>org.perf4j</groupId>
<artifactId>perf4j</artifactId>
<version>${perf4j.version}</version>
</dependency>
</dependencies>
Here is the aspect beans file :
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="true">
<aop:include name="timingAspect"/>
</aop:aspectj-autoproxy>
<!--<context:load-time-weaver/> -->
<!-- The perf4j aspect -->
<bean id="timingAspect" class="org.perf4j.log4j.aop.TimingAspect"/>
Here is how I bring that XML beans file in (within the spring application context file) :
<import resource="aspectBeans.xml" />
Now, the application compiles, it runs, and it prints my System.out.println line, but I am seeing absolutely nothing related to timing.

Related

Spring validation annotations (#Size, #NotEmpty, #Max...) not working in my MVC project

I'm trying to get my head around an MVC project. There is a form page that the user fills out and they end up in an object of the Employee class.
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
Here is what the class part looks like. It can be seen that I set parameter validation above some of the fields.
import jakarta.validation.constraints.*;
...
public class Employee {
#Size(min = 2, message = "Name must be min 2 symbols")
private String name;
#NotBlank(message = "surname is required field")
private String surname;
#Max(value = 100,message = "max is required field")
private int salary;
....
}
Here's what the html page looks like with the form filled out. It can be seen that the form "errors" is used to catch errors.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
...
<form:form action="show" modelAttribute="employee">
Name <form:input path="name"/>
<form:errors path="name" />
<br>
<br>
Surname <form:input path="surname"/>
<form:errors path="surname"/>
<br>
<br>
Salary <form:input path="salary"/>
<form:errors path="salary" />
...
Well, this is how the method looks like, which redirects to another page if all the fields in the form have been validated.
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask-page";
} else {
return "show-page";
}
The problem is that the annotations specified above the fields in the class do not work. Here is the output of the showDetails method, which shows that data is being entered that does not match the specified restrictions in the Size, Name annotations. You can also see that bindingResult indicates no errors.
...
surname length = 0
name length = 0
bindingResult.hasErrors() = false
Does anyone know why these annotations don't work?
In my view, validation should not pass and the user should be returned the original form with an error on incorrectly filled fields
UPD.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pablinho.spring.mvc</groupId>
<artifactId>spring_mvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<name>spring_mvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>javax.servlet</groupId>-->
<!-- <artifactId>servlet-api</artifactId>-->
<!-- <version>2.5</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-validator</artifactId>-->
<!-- <version>6.1.0.Final</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>spring_mvc</finalName>
</build>
</project>
UPD. Add web.xml, applicationContext.xml and conroller MyController.java
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>spring-cource-mvc</display-name>
<absolute-ordering />
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.pablinho.spring.mvc" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
MyContoller.java
package com.pablinho.spring.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.validation.Valid;
#Controller
#RequestMapping("/")
public class MyController {
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask=page";
} else {
return "show-page";
}
}
}

#Before Advice Annotation not Applied in the Spring Application

I have been trying to develop a small application that demonstrates the #Before Annotation , but its not working
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>aopdemo</groupId>
<artifactId>aopdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
AccoutDAO.java file is
package org.java.aop.dao;
import org.springframework.stereotype.Component;
#Component
public class AccoutDAO {
public void addAccount()
{
System.out.println("Adding account"+getClass());
}
}
The Aspect configuration file is
package org.java.aop.aspects;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class MyAspects {
#Before("execution(public void addAccount())")
public void display()
{
System.out.println("=====================>>CALLING Aspects");
}
}
The spring config file(spring-config.xml) is
<?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:mvc="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>
</beans>
And finally my main code is
package org.java.aop;
import org.java.aop.dao.AccoutDAO;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainDemo {
public static void main(String arg[])
{
try
{
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
AccoutDAO accoutDAO=context.getBean("accountDAO",AccoutDAO.class);
accoutDAO.addAccount();
context.close();
}
catch (Exception e)
{
System.out.print(e);
}
}
}
I am able to get the output as "INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Adding accountclass org.java.aop.dao.AccoutDAO
Nov 22, 2018 2:06:14 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext#1ed6993a: startup date [Thu Nov 22 02:06:14 IST 2018]; root of context hierarchy"
But i could not able to get the output for #Before Annotation.Kindly tell me whats wrong in this code
The above problem is resolved by adding component scan in spring-config.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:mvc="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>
<context:component-scan base-package="org.java.aop"/>
</beans>

Query failed with error code 16550 and error message 'not authorized for query on myCollection

I have a spring boot rest application that interacts with MongoDB but when I invoke the controller method, I give the following exception :
com.mongodb.MongoQueryException: Query failed with error code 16550 and error message 'not authorized for query on 'tenant' on server 172.16.233.128:27017
at com.mongodb.connection.ProtocolHelper.getQueryFailureException(ProtocolHelper.java:131) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:295) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:54) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.query(DefaultServerConnection.java:212) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:525) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:81) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo.execute(Mongo.java:836) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo$2.execute(Mongo.java:823) ~[mongo-java-driver-3.4.2.jar:na] .....
these are classes and configuration
pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.concretepage</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-mongodb</name>
<description>Spring Boot Demo Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath*:properties/application.properties"/>
<context:component-scan base-package="com.faracloud.mongodbop.controller" />
<mvc:annotation-driven />
<mongo:mongo id="mongo" host="${catalog.mongodb.host}" port="${catalog.mongodb.port}" />
<mongo:db-factory id="mongoDbFactory" dbname="${catalog.mongodb.database}" mongo-ref="mongo"
username="${catalog.mongodb.user}"
password="${catalog.mongodb.password}"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.faracloud.mongodbop.repository"
mongo-template-ref="mongoTemplate" />
MongoApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#ImportResource("classpath:spring/mongodbop-context.xml")
public class MongoApp {
public static void main(String[] args) {
ApplicationContext ctx =SpringApplication.run(MongoApp.class,
args);
}
}
TenantRepository.java
import com.faracloud.mongodbop.model.Tenant;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface TenantRepository extends MongoRepository<Tenant,
String> {
}
and Rest Controller
import com.faracloud.mongodbop.model.Tenant;
import com.faracloud.mongodbop.repository.TenantRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class StatisticController {
#Autowired
TenantRepository repo;
#RequestMapping("/greeting")
public List<Tenant> greeting() {
return repo.findAll() ;
}
}
please give me some advice how to handle this error
My problem was solved using these dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
instead of using mongoTemplate and mongoDbFactory for host,dbnameand credentials, I used following configurations in application.properties
spring.data.mongodb.host=x.x.x.x
spring.data.mongodb.port=27017
spring.data.mongodb.database=xxx
spring.data.mongodb.username=***
spring.data.mongodb.password=***
Thank you reviewers.

How do configure struts convention plugin with struts-spring plugin with Action class mapped with annotations

I am trying to configure spring plugin with strut 2 application which is already running with convention plugin, so I am using annotations. I am using ExtJs for my form submission which was initially working well until I introduced the spring plugin, now the the ajax request cannot locate the actions and it's not showing any response in firebug.
pom.xml
<!-- struts 2 dependencies -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<!-- Import the CDI API -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-cdi-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0-SP1</version><!--$NO-MVN-MAN-VER$-->
<scope>provided</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<constant name="struts.devMode" value="true" />
<constant name="struts.convention.result.path" value="/content" />
<constant name="struts.multipart.saveDir" value="/tmp" />
<constant name="struts.multipart.maxSize" value="4194304" />
<constant name="struts.action.excludePattern" value="/api/.*?" />
</struts>
web.xml
<display-name>Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/api</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
Action Class
#Namespace("/units")
#Result(
type = "stream",
params = {
"inputName", "stream"
}
)
public class PropertyTypeAction extends BaseAction implements ActionImpl{
#PersistenceUnit
private EntityManagerFactory emf;
#Action(value="add")
public String add() {
.......
}
}
Ajax Request firebug report, XML tab
XML Parsing Error: no element found Location: moz-nullprincipal:{7fc640bd-f293-4956-8cf2-178765cec735} Line Number 1, Column 1:
My question is how can I configure struts-spring plugin to work with struts convention plugin with the annotations.
You are importing both the struts2-spring-plugin, and the struts2-CDI-plugin.
Don't.
Choose only one of the above plugins, and then configure it properly:
To use the CDI plugin, simply import the JAR with Maven and start annotating the objects you want to be injected with the (right) #Inject annotation.
To use the Spring plugin, import the JAR, add the ContextLoaderListener in web.xml (that you have already set), and specify that you want to use Spring as objectFactory in struts.xml, with the constant:
<constant name="struts.objectFactory" value="spring" />
IMHO the CDI plugin is the better option, if you are using Java EE >= 6.

Could not load TestContextBootstrapper - Spring Unit testing

I have to execute Unit test on one of my Dao classes using Spring. Here is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:app-config.xml"})
#ActiveProfiles("local")
public class HouseDaoTest {
#Autowired
HouseDataDao houseDataDao;
#Test
public void saveTest(){
HouseData data = new HouseData();
Address add = new Address();
// Truncating for sake of simplicity
houseDataDao.save(data);
}
}
And My bean configuration files:
app-config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="BeanConfiguration-localhost.xml"/>
<import resource="BeanConfiguration-production.xml"/>
</beans>
BeanConfiguration-localhost.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans profile="local"
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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<tx:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/dbtest" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- Tuncated for sake of simplicity -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Project Specific Beans -->
<bean id="HouseDataDao" class="com.datasaver.dao.HouseDataDaoImpl"></bean>
</beans>
Where BeanConfiguration-production.xml is same as above except for <beans profile="production" ... in it.
When I simply execute a maven test doing mvn test it fails throwing the following exception:
java.lang.IllegalStateException: Could not load TestContextBootstrapper [class org.springframework.test.context.support.DefaultTestContextBootstrapper]. Specify #BootstrapWith's 'value' attribute or make the default bootstrapper class available.
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:87)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:102)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:124)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:115)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:29)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:21)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:250)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.BeanUtils.instantiateClass(Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Object;
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:81)
... 25 more
It looks like I am missing a dependency or something, because the stacktrace contains Caused by: java.lang.NoSuchMethodError: org.springframework.beans.BeanUtils.instantiateClass.
Here is the Spring's dependency list in my pom.xml:
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
...
It is probably a version conflict since you are using a old version of base spring (2.5.6) with very new one (4.1.4.RELEASE) for your test en context includes
In my case it was a version conflict caused by activemq-all. That dependency (5.12.2 in my case) includes an incompatible version of spring (I just upgraded to spring 4.3.4). So, save yourself a few hours of debugging and check not only the Dependency Hierarchy in your favorite IDE, but also look inside those jar files to see if any are embedding org.springframework packages.
Maarten is correct. Here is my new list of dependencies in pom.xml which worked for me:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>

Resources