Issues using Spring's DomainClassConverter in Spring MVC - spring

I am trying to use Spring's DomainClassConverter feature with my Spring MVC project. (I have only very basic knowledge of Spring MVC and Spring, apologies in advance for any naive question here).
From the API docs:
The DomainClassConverter allows you to use domain types in your Spring MVC controller
method signatures directly, so that you don't have to manually lookup the instances via
the repository: (PS: Example 1.20)
What I understood from the above is that I don't have to write a finder method and the Spring supplies the User object. So these are the steps I did:
Included the below line of XML in applicationcontext.xml.
<bean class="org.springframework.data.web.config.SpringDataWebConfiguration" />
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.rl.userservice.controller.UserConverter"/>
</list>
</property>
Included this dependency in my pom.xml per the Spring Data REST doc:
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</dependency>
</dependencies>
My controller looks like the below:
#Controller
#RequestMapping(value = "/api/newuser")
public class NewUserServiceController {
#Autowired
NewUserRepository newUserRepository;
#RequestMapping("/{id}")
public String showUserForm(#PathVariable("id") NewUser newUser, Model model) {
model.addAttribute("newUser", newUser);
return "userForm";
}
}
Repository is like this:
#Repository
public interface NewUserRepository extends JpaRepository<NewUser, Integer> {
}
This is my converter service:
final class UserConverter implements Converter<Integer, NewUser> {
NewUserRepository newUserRepository;
public NewUser convert(Integer username) {
return newUserRepository.findOne(username);
}
}
When I run the program tomcat starts successful, but when accessing the URL localhost:8080/userservice/api/newuser/1 I get the below exception:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type
'com.mpp.userservice.domain.NewUser'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type
[java.lang.String] to required type
[com.mpp.userservice.domain.NewUser]: no matching editors or
conversion strategy found
org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:71)
org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:45)
org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:595)
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:101)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type
[com.mpp.userservice.domain.NewUser]: no matching editors or
conversion strategy found
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:264)
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:93)
org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:45)
org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:595)
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:101)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.
mpp.
Though not the best code, here's my controller:
public #ResponseBody ResponseEntity<ModelMap> getUserTypeJSON(#PathVariable("userID" String userID, HttpServletResponse response) {
UserType UserType = UserTypeRepository.findOne(id);
model.addAttribute("Name",UserType.getName());
...
}
There is an example here that I referenced, but this is using custom converter but does not seem to be using the domain converter service. Please advise. Is this the way to go if I want to reduce boilerplate code of writing CRUD operations? What is the real benefit of this DomainClassConverter when I can get the data in in the other way?
Updated per Oliver Gierke suggestion - still does not work, same error
The document describes:
<mvc:annotation-driven conversion-service="conversionService" />
<bean class="org.springframework.data.repository.support.DomainClassConverter">
<constructor-arg ref="conversionService" />
</bean>
So I updated my applicationcontext.xml as below, but the same issue:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean class="org.springframework.data.repository.support.DomainClassConverter">
<constructor-arg ref="conversionService" />
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.rl.userservice.controller.UserConverter"/>
</list>
</property>
</bean>
Still the same issue.
Update: DomainClassConverter works with Java Config, but not the XML way (at least experimented with a lot of combinations suggested here and else where on the internet). Just for the others who might be interested and get some useful info here's the code used.
pom.xml (Might require clean-up)
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.0.M1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
The controller file (Might require clean-up)
#RequestMapping("/domain/{id}")
public #ResponseBody ResponseEntity<ModelMap> showDomainUserForm(#PathVariable("id") User userMatch, HttpServletResponse response) {
// some code omitted…
ModelMap model = new ModelMap();
model.addAttribute("DOMAIN-MAP","Domain Controller Service");
model.addAttribute("Name",userMatch.getName());
model.addAttribute("Phone",userMatch.getPhone());
// some code omitted…
}
The Java Config file assembled using examples from resource1 and resource2.
(Might require clean-up)
package com.rl.userservice.controller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.support.DomainClassConverter;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
#Configuration
#ComponentScan
#EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport{
#Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
handlerMapping.setUseSuffixPatternMatch(false);
handlerMapping.setUseTrailingSlashMatch(false);
return handlerMapping;
}
#Bean
public DomainClassConverter<?> domainClassConverter() {
return new DomainClassConverter<FormattingConversionService>(mvcConversionService());
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Add the below bean definition in the applicationContext.xml
<bean class="com.rl.userservice.controller.WebConfig"/>

A URL is a String, so {id} is a String too. Therefore your service must be able to convert a String to NewUser, not an Integer as yours does.

Please have a look at the relevant section of the reference documentation to find out about the correct way to configure the DomainClassConverter.

The ref says
Currently the repository has to implement CrudRepository to be
eligible to be discovered for conversion.
Shouldn't that be the reason?

This configuration sets up a custom conversion service and passes it to annotation scanning mechanism that detects and sets up the controllers:
<bean name="conversionService" class="rest.gateway.services.MyConversionService"/>
<mvc:annotation-driven conversion-service="conversionService" />
And this is the code for the custom controller, customer being a domain class like User:
public class MyConversionService extends DefaultConversionService {
public MyConversionService() {
super();
addConverter(String.class, Customer.class, new Converter<String, Customer>() {
#Override
public Customer convert(String source) {
return new Customer("123456","Doe","John");
}
});
}
}
Have a try with this because this is working for version 2.0.0.M1:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.0.M1</version>
</dependency>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

Related

Problems using Springboot autoconfiguration to connect to SQL-Server in a FUSE EAP environment

This is likely to be a misconception on my part when it comes to working with SpringBoot on FUSE EAP environments. I've been trying to deploy a service, which I've developed following the RedHat documentation and the archetypes/examples I've found online that mix Camel and SpringBoot, but to no avail.
From what I understand, when creating a connection to a JNDI datasource, which has been configured and tested in the EAP Fuse server, I can use the application.properties, or application.yml, to have the spring application autoconfigure the connection. In my case, it's required that I use #PersistenceContext to invoke the EntityManager, since the CRUD operations that the extending JpaRepository don't really cover the needs.
As per RedHat's documentation, FUSE 7.2 has been installed in EAP 7.1 and the POM is using the org.jboss.redhat-fuse.fuse-springboot-bom version 7.2.0.fuse-720020-redhat-00001.
I've tried using spring's autoconfiguration, a manual configuration declaring a #Configuration class, a manual configuration by declaring the database connection in the camel-context.xml file, and some other minor tests.
The errors vary depending on whether I try delpying the .jar or .jar.original, generated by having the spring-boot-maven-plugin with the repackage execution goal, errors obtained up to this point are:
NullPointer because EntityManager em is null (.jar.original)
java.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder (.jar.original, when there's a manual configuration of the datasource, be it in a #Configuration annotated java class, or in the camel-context.xml using Spring DSL)
java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl (.jar with all dependencies packaged)
Here are snippets of my program, which include the POM, Application.java and the component which is trying to get the EntityManager, will be happy to provide more snippets if it's not enough/unclear.
POM.xml
...
<properties>
<fuse.version>7.2.0.fuse-720020-redhat-00001</fuse.version>
...
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
...
<build>
<defaultGoal>spring-boot:run</defaultGoal>
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.16.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
application.properties
spring.datasource.jndi-name=jdbc:sqlserver://ip:1433;DatabaseName=dbname
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.generate-ddl=false
Application.java
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
camel-context.xml
<beans ...>
...
<camelContext id="identidades_financieras" xmlns="http://camel.apache.org/schema/spring">
<onException>
<exception>java.lang.Exception</exception>
<handled>
<constant>true</constant>
</handled>
<setHeader headerName="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
<setBody>
<simple>${exception.message}</simple>
</setBody>
</onException>
<restConfiguration apiContextPath="/openapi.json"
bindingMode="json" component="undertow"
contextPath="/restservice/api_v1" enableCORS="true">
<dataFormatProperty key="prettyPrint" value="true"/>
</restConfiguration>
<rest enableCORS="true" id="rest-for-openapi-document" path="/openapi">
<get id="openapi.json" produces="application/json" uri="openapi.json">
<description>Gets the OpenAPI document for this service</description>
<route id="route-for-openapi-document">
<setHeader headerName="Exchange.CONTENT_TYPE" id="setHeader-for-openapi-document">
<constant>application/vnd.oai.openapi+json</constant>
</setHeader>
<setBody id="setBody-for-openapi-document">
<constant>resource:classpath:openapi.json</constant>
</setBody>
</route>
</get>
</rest>
<rest bindingMode="auto" enableCORS="true"
id="rest-b5d099c1-1996-458b-b5db-34aadc57a548" path="/">
<get id="customPaginatexxxVO" produces="application/json" uri="/xxx">
<to uri="direct:customPaginatexxxVO"/>
</get>
...
<route id="route-28f4489d-b354-401b-b774-6425bec1c120">
<from id="from-17c4205f-8d28-4d3d-a265-cb1c38c9bc32" uri="direct:customPaginatexxxVO"/>
<log id="customPaginatexxxVO-log-1" message="headers ====> pageSize: ${header.pageSize} - pageNumber: ${header.pageNumber}"/>
<bean id="to-ee6565efaf-de46-4941-b119-be7aaa07d892"
method="paginate" ref="genericService"/>
<log id="customPaginatexxxVO-log-2" message="${body}"/>
</route>
<beans/>
genericService.java
#Service
public class genericServiceImpl implements genericService {
#Autowired
private genericDAO dao;
...
#Override
public xxxVO paginate(Map<String, Object> reqHeaders) {
... pageProps are defined using reqHeaders ...
xxxVO paginated = dao.customPagination(pageProps);
return paginated;
}
...
}
genericDAOImpl.java, which errors out when anything regarding em is invoked.
#Repository
public class genericDAOImpl implements genericDAO {
#PersistenceContext //when manually configured, I've added the (unitName="") in reference to the persistence unit, from my understanding, since only one datasource was created, this should pick up by default
private EntityManager em;
...
#Override
public xxxVO customPagination(paginateProps pageProps) {
xxxVO result = null;
try {
CriteriaBuilder paginationBuilder = em.getCriteriaBuilder();
CriteriaQuery<T> paginationQuery = paginationBuilder.createQuery(entity.class);
Root<T> entityClass = paginationQuery.from(entity.class);
paginationQuery.select(entityClass);
... some settings with pageProps ...
TypedQuery<T> query = em.createQuery(paginationQuery);
entityList = query.getResultList();
... entityList is transformed to xxxVO ...
} catch (Exception e) {
LOG.error("caught something");
e.printStackTrace();
}
return result;
}
...
As stated before, I've been getting numerous different errors depending on the options I've tried, and most of them clearly come down to misconfiguration, or not deploying correctly, I'm still somewhat inexperienced when it comes to SpringBoot and Camel, and different things I've read on the internet have created some confusion. Just to make sure, the pagination method, while very snipped out, should be working, if it had a not nulled EntityManager.
Here are a couple of the logs:
When deplying .jar (fat jar with all dependencies), which from the tests I've made, deploys correctly using java -jar, but not in the fuse eap service
09:16:01,937 WARN [org.springframework.context.support.GenericApplicationContext] (MSC service thread 1-3) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
09:16:01,940 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Cannot create camel context: identidades_financieras-1.0-SNAPSHOT.jar
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:71)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAO from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
...
When deploying .jar.original (basically, just the java) with a manually configured DataSource and EntityManagerFactory. From what I understand, the service is expecting org.springframework.boot dependencies to exist on the server. After checking the modules, there is no org.springframework.boot module in the fuse layer. Is this intended?
09:50:17,265 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1978)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1490)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:96)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.wildfly.extension.camel.SpringCamelContextBootstrap$1.run(SpringCamelContextBootstrap.java:90)
at org.wildfly.extension.camel.proxy.ProxyUtils$1.invoke(ProxyUtils.java:51)
at com.sun.proxy.$Proxy68.run(Unknown Source)
at org.wildfly.extension.camel.proxy.ProxyUtils.invokeProxied(ProxyUtils.java:55)
at org.wildfly.extension.camel.SpringCamelContextBootstrap.createSpringCamelContexts(SpringCamelContextBootstrap.java:87)
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:58)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
... 3 more
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:412)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:400)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 27 more
Finally, when uploading the .jar.original using only the Spring autoconfigure, the EM is null, using Postman I get a status 500 and "No response available" when I consume the REST
java.lang.NullPointerException
at com.example.dao.genericDAOImpl.customPagination(GenericDAOImpl.java:252)
The line makes reference to CriteriaBuilder paginationBuilder = em.getCriteriaBuilder(), or any other place where a EM method is invoked.
Thank you for your time! Any comment is appreciated...
There is no support for Spring Boot with Fuse EAP and the Camel subsystem. Hence why you do not see any org.springframework.boot dependencies in the Fuse module layer.
If you are going to deploy Camel Spring Boot applications into EAP, it's best you either disable the Camel subsystem for your deployment or avoid installing the subsystem entirely.
This is by no means a solution to the issue I was having, I believe this to be but a temporary patch on my code since the 7.4 version of Fuse will supposedly support SpringBoot 2.1.x or something of the like, but doing the following allowed me to create the database connection and move on with my life. I will not mark this as the acceptable answer, unless I'm told that this is the only way.
In the Application.java, I straight up disabled the SpringBootServletInitializer. Full disclosure, I straight up have no idea of the impact that doing this could have in an application, but the dependency was troubling while I was trying to deploy.
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application {//extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I created a persistence.xml file where I configured the name of persistence unit and selected the package containing the entities (or listed them, both worked).
In the camel-context.xml I declared the following before the tag
<bean class="org.apache.camel.component.jpa.JpaComponent" id="jpa">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="transactionManager" ref="jpaTxManager"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="jpaTxManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="PERSISTENCE UNIT NAME IN PERSISTENCE.XML"/>
</bean>
<bean class="org.apache.camel.spring.spi.SpringTransactionPolicy" id="requiredPolicy">
<property name="transactionManager" ref="jpaTxManager"/>
<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
</bean>
I created a java class responsible for the creation of the EntityManager, it is very important that the class is #Stateless (EJB), and that the connection to the persistence unit is made static.
#Stateless
public class persistenceUnitEntityManagerImpl implements IfEntityManager{
private static EntityManager em;
static {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE UNIT NAME");
em = entityManagerFactory.createEntityManager();
}
public void setEntityManager( EntityManager em ) {
persistenceUnitEntityManagerImpl.em = em;
}
public EntityManager getEntityManager() {
return persistenceUnitEntityManagerImpl.em;
}
}
In the beans where the database connection was needed, in my case, an #Component (should work just as well in a #Repository), I added the following:
private IfEntityManagerImpl IfEntityManager;
#PostConstruct
public void init() {
this.persistenceUnitEntityManagerImpl = new persistenceUnitEntityManagerImpl();
}
And whenever the EntityManager needs to be called, I can use persistenceUnitEntityManagerImpl.getEntityManager()
Just to make sure that the component isn't creating a new connection/entity manager/whatever, you can add a LOG to the #PostConstruct init, if your bean is a singleton (should be by default, I believe) you will never get that LOG or printline.

Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource

I am new to Spring. I am creating simple project in which I just call generateOutout() method using beans.
IOutputGenerator Interface:
package mian.java;
public interface IOutputGenerator {
public void generateOutput();
}
CsvOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class CsvOutputGenerator implements IOutputGenerator{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
JsonOutputGenerator.java (implements IOutputGenerator ):
package mian.java;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
OutputHelper.java:
package mian.java;
public class OutputHelper {
IOutputGenerator outputGeneratorCsv;
IOutputGenerator outputGeneratorJson;
public void generateOutput(){
outputGeneratorCsv.generateOutput();
outputGeneratorJson.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGeneratorCsv,IOutputGenerator outputGeneratorJson){
this.outputGeneratorCsv = outputGeneratorCsv;
this.outputGeneratorJson = outputGeneratorJson;
}
}
AppViaSpring.java (Main class):
package mian.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppViaSpring {
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Spring-Common.xml (Bean Class in main.resources package):
<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-2.5.xsd">
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="main.java.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="main.java.JsonOutputGenerator" />
</beans>
and Error is :
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [main.java.OutputHelper] for bean with name 'OutputHelper' defined in class path resource [Spring-Common.xml]; nested exception is java.lang.ClassNotFoundException: main.java.OutputHelper
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1141)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:758)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:422)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at mian.java.AppViaSpring.main(AppViaSpring.java:10)
Caused by: java.lang.ClassNotFoundException: main.java.OutputHelper
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
... 9 more
you forgot to add the JsonOutputGenerator bean for OutputHelper
try this:
<bean id="OutputHelper" class="main.java.OutputHelper">
<property name="outputGeneratorCsv" ref="CsvOutputGenerator" />
<property name="outputGeneratorJson" ref="JsonOutputGenerator" />
</bean>
note you can also use context.getBean(OutputHelper.class), no casting will be required
edit:
on the further look at the problem. The setter you are using has two arguments which violates javaBean convention. There are few options.
1. You simply pass the map to the setter.
2. Create setter for each generator field.
3. You inject outputGeneratorCsv and outputGeneratorJson in the constructor - i would recommend that. In that case you would have to add constructor with two arguments (like your setter method) and modify the spring context xml to something like that:
<bean id="OutputHelper" class="main.java.OutputHelper">
<constructor-arg ref="outputGeneratorCsv"/>
<constructor-arg ref="outputGeneratorJson"/>
</bean>
here also some more info, why to use constructor injections:
We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).
Setter injection versus constructor injection

Spring 4.1.5.RELEASE fails to do dependency injection for SessionFactory of Hibernate 4.3.8.Final

Question is not a duplicate as Hibernate is involved
As the James' answer partially solved the problem, I accepted it and opened a new question, please follow up here
I am trying to inject SessionFactory into a repository class; however, it looks like it does not work as the code returns NullPointer exception.
I cleaned and rebuilt the project but the issue still exist. I also put #Autowired on the setSessionFactory method but did not help.
Interface
public interface TestRep {
public void get(int id);
}
Class
#Repository
public class TestRepImpl implements TestRep{
#Autowired
SessionFactory sessionFactory;
public TestRepImpl() {
}
public TestRepImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
public void get(int id) {
String hql = "from Business where id=" + id;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
....
pr-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config/>
.....
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="TestRep" class="com.project.repository.TestRepImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
StackTrace
Mar 10, 2015 12:22:21 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [pr] in context with path [/project] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.project.repository.TestRepImpl.get(TestRepImpl.java:39)
at com.project.web.MainController.index(MainController.java:17)
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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Jars
MainController
#Controller
public class MainController {
#RequestMapping("/{viewName}.htm")
public String index(#PathVariable(value = "viewName") String viewName) {
System.err.println(viewName);
Test test = new Test();
test.get(1);
if (isValidView(viewName)) {
return viewName;
}
return null;
}
#RequestMapping("/{viewName}/{viewName2}") //suburb/catname
public String index(#PathVariable(value = "viewName") String viewName, Model model) {
System.err.println(viewName);
if (isValidView(viewName)) {
model.addAttribute("viewName",viewName);
return "page";
}
return null;
}
private boolean isValidView(String viewName) {
switch (viewName) {
case "index":
case "aboutus":
return true;
}
return false;
}
}
Test
#Service
public class Test {
public void get(int i){
TestRepImpl test = new TestRepImpl();
test.get(i);
}
}
Hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">12</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.myproject.model.MyTable" />
....
You need to use Autowiring everywhere or your program won't work. Spring can only autowire beans that are present in the Spring application context, which is what your #Controller, #Service and #Repository annotations are supposed to do. However, these annotations are meaningless without a <context:component-scan base-package="your.base.package"> tag in your config XML.
So, assuming that your controller, service and DAO are all somewhere in the package com.repository, you need to add this line to your XML config.
<context:component-scan base-package="com.repository"/>
What this does is tells Spring to recursively search inside the foo.bar.baz package (and all sub-packages) for classes annotated with #Controller, #Service, #Repository and #Component, instantiate a singleton instance of them and make them eligible to be autowired into other classes.
You also need to modify your controller and service classes to use #Autowired. Spring can't manage your classes if you instantiate them with the new keyword. These beans are singletons (only one instance of them should ever exist in your program) for a reason.
Your controller needs to change as follows.
#Controller
public class MainController {
#Autowired
private TestService testService;
#RequestMapping("/{viewName}.htm")
public String index(#PathVariable(value = "viewName") String viewName) {
System.err.println(viewName);
testService.get(1);
if (isValidView(viewName)) {
return viewName;
}
return null;
}
#RequestMapping("/{viewName}/{viewName2}") //suburb/catname
public String index(#PathVariable(value = "viewName") String viewName, Model model) {
System.err.println(viewName);
if (isValidView(viewName)) {
model.addAttribute("viewName",viewName);
return "page";
}
return null;
}
private boolean isValidView(String viewName) {
switch (viewName) {
case "index":
case "aboutus":
return true;
}
return false;
}
}
Notice that you Autowire your service class into your controller.
Your service class needs to implement an interface. Spring does all this autowiring magic using interfaces. You cannot autowire a class that does not implement an interface, unless you specifically create an instance of that class in your XML config.
Your service class needs to change as follows:
#Service
public class TestServiceImpl implements TestService {
#Autowired
private TestRepDao testDao;
#Transactional
public void get(int i){
testDao.get(i);
}
}
and create an interface called TestService.
public interface TestService{
public void get(int i);
}
and then your DAO becomes
#Repository
public class TestRepDaoImpl implements TestRepDao{
#Autowired
private SessionFactory sessionFactory;
public void get(int id) {
String hql = "from Business where id=" + id;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
}
}
which implements the interface TestRepDao:
public interface TestRepDao{
public void get(int id);
}
you can also remove the declaration of
<bean id="TestRep" class="com.project.repository.TestRepImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
from your XML configuration.
As you can see I've changed a few class names to better fit with the Spring convention. Your application is supposed to layer down from Controller to Service Class to DAO and back out again. This should work providing you follow the steps I've laid out here.
A few things to keep in mind:
Spring hates the new keyword. If you find yourself using it, you are probably doing something wrong.
There is only ever one instance of any of your classes that Spring picks up with the component scan in your entire application. DO NOT use these classes to store persistent data or states. That path is full of threading issues, race conditions and pits full of acid spiders.
Read and re-read the documentation, these are not easy concepts to pick up if you have never used Spring before. Spring is super easy to use, once you understand how it works, and how it expects you to use it.
Spring works on interfaces. If your class doesn't implement an interface, Spring can't proxy it without using AspectJ Load Time Weaving, which is a conversation for another day, and not something you should be using, just starting out. If you don't know why Spring needs to create a proxy of your object, you need to re-read the documentation until you understand the application context.
I moved the #Transactional annotation into the Service class. This is because the DAO should only be concerned with accessing and retrieving the data from the database, NOT having to manage the connection/session to the database, that is the job of the service class.
I'm guessing you started using the new keyword after hitting exceptions saying something similar to
No qualifying bean of type found for dependency TestService.
This is Spring telling you that it doesn't have a bean that can be autowired into the TestService field on whatever class. Listen when Spring is telling you things, it will save you a lot of bother.
Don't be discouraged, I faced all these problems when I was trying to learn how to use Spring, but I got through it and Spring is second nature to me now.

How do I get my Spring Aspect to kick in for a #Valid annotation on a service method?

We're using Spring 3.2.11.RELEASE and Maven 3.0.3. I'm trying to set up validation of a parameter being passed into a service method. The method is below. Notice the #Valid annotation.
package org.mainco.subco.mypck.service;
#Service
#RemoteProxy
#Transactional
public class MypckServiceImpl implements MypckService {
#RemoteMethod
#Override
public String myMethod(#Valid final MyObjectDto request) {
// ...
}
}
Here is the aspect I have set up to help validate the object:
#Aspect
#Component
public class MyObjectValidatingAspect extends AbstractDWRAspectValidator<MyObjectDto>
{
#Before("execution(* org.mainco.subco.mypck.service.MypckService.myMethod(..))")
public void validateBefore(JoinPoint jp)
{
errors = new ArrayList<String>();
final MyObjectDto request = validate(jp);
validateMyObject(request);
throwErrors();
} // validateBefore
This is in included in my application context file:
<global-method-security pre-post-annotations="enabled">
</global-method-security>
<aop:aspectj-autoproxy/>
And this is what I've included in the Maven pom.xml file:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.2</version>
</dependency>
Unfortunately when the method is invoked, the aspectj's validateBefore is never called. What else do I need to do so that this gets invoked?
Since Spring 3.1 there is the MethodValidationInterceptor which basically does what you want to achieve yourself. To have this interceptor applied the only thing you need to do is to register a MethodValidationPostProcessor in your application context.
By default it will check for the #Validated annotation from Spring but you can instruct it to scan for the #Valid annotation.
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
<property name="validatedAnnotationType" value="javax.validation.Valid" />
<property name="validator" ref="refToYOurLocalValidatorFactoryBean" />
</bean>
If you don't specify a validator the default JSR-303 validator mechanism will be used (or the more hibernate specific one if that is available). But I can imagine you want to reuse the already configured instance.

Shiro Authorization Permission check using Annotation not working

Platform: Shiro 1.1.0, Spring 3.0.5
I'm trying to secure the MVC Controller methods using Shiro annotation. However something is wrong with annotations. Regular calls are just working OK. There is nothing specific in Shiro debug also.
My shiro configuration:
<!-- Security Manager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="sessionMode" value="native" />
<property name="realm" ref="jdbcRealm" />
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- Caching -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehCacheManager" />
</bean>
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO" />
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="sessionDAO" ref="sessionDAO" />
</bean>
<!-- JDBC Realm Settings -->
<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
<property name="name" value="jdbcRealm" />
<property name="dataSource" ref="dataSource" />
<property name="authenticationQuery"
value="SELECT password FROM system_user_accounts WHERE username=? and status=1" />
<property name="userRolesQuery"
value="SELECT role_name FROM system_roles r, system_user_accounts u, system_user_roles ur WHERE u.user_id=ur.user_id AND r.role_id=ur.role_id AND u.username=?" />
<property name="permissionsQuery"
value="SELECT permission_name FROM system_roles r, system_permissions p, system_role_permission rp WHERE r.role_id=rp.role_id AND p.permission_id=rp.permission_id AND r.role_name=?" />
<property name="permissionsLookupEnabled" value="true"></property>
</bean>
<!-- Spring Integration -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after
the lifecycleBeanProcessor has run: -->
<bean id="annotationProxy"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor" />
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
<!-- Secure Spring remoting: Ensure any Spring Remoting method invocations
can be associated with a Subject for security checks. -->
<bean id="secureRemoteInvocationExecutor"
class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
<property name="securityManager" ref="securityManager" />
</bean>
<!-- Shiro filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/dashboard" />
<property name="unauthorizedUrl" value="/error" />
<property name="filterChainDefinitions">
<value>
<!-- !!! Order matters !!! -->
/authenticate = anon
/login = anon
/logout = anon
/error = anon
/** = authc
</value>
</property>
</bean>
I can get the following working correctly:
#RequestMapping(value="/form")
public String viewPatientForm(Model model, #RequestParam(value="patientId", required=false) Long patientId){
if (!SecurityUtils.getSubject().isPermitted("hc:viewPatient")){
logger.error("Operation not permitted");
throw new AuthorizationException("No Permission");
}
}
But the below doesn't work:
#RequiresPermissions("hc:patientView")
#RequestMapping(value="/form")
public String viewPatientForm(Model model, #RequestParam(value="patientId", required=false) Long patientId){
Am I missing something? Please help.
You were absolutely right. After seeing your comment, I started giving it a thought. Well then I found out that it was NOT an implementation problem with Shiro, but the jar dependecies were not properly configured. Shiro's pom.xml should have dependency for cglib2 too.
So the below changes worked for me :
Include all these four jar files.
aspectjrt-1.6.11.jar,
aspectjweaver-1.6.12.jar,
cglib-2.2.2.jar,
asm-3.3.1.jar,
If you are using maven then :
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
And finally placing the aop:aspectj-autoproxy in the webApplicationContext.xml
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Annotation, so that it's easier to search controllers/components -->
<context:component-scan base-package="com.pepsey.soft.web.controller"/>
Note : The above two configuration should be placed together in the same spring-webApplicationContext.xml. Otherwise it won’t work. Moreover remove context:annotation-config if you have used it in your config. context:component-scan already scans all annotations.
Once you start testing , set your log4j to debug or (better) trace mode. Whenever you are starting your server you will find somewhere the following entry in your logs :
08:16:24,684 DEBUG AnnotationAwareAspectJAutoProxyCreator:537 -
Creating implicit proxy for bean 'userController' with 0 common
interceptor and 1 specific interceptors
Guess Shiro was built when Spring 2.0 was in place. Shiro’s annotations (RequiresRoles etc…) works well for the spring container managed beans (service layer), but it does not work with #Controller annotation. This is due to the fact that #Controller is being component scanned by spring framework. I used AOP to resolve the issue. Below is the solution which worked for me.
For the below solution to work you have to include the below four jars:
aspectjrt-1.6.11.jar
aspectjweaver-1.6.12.jar
cglib-2.2.2.jar
asm-3.3.1.jar
If you are using maven then below configuration would be helpful.
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
Below is a controller class
import org.apache.shiro.authz.annotation.RequiresRoles;
#Controller
public class PatientController {
#RequiresRoles(“admin,warden”)
#RequestMapping(value="/form")
public String viewPatientForm(Model model, #RequestParam(value="patientId", required=false) Long patientId){
return “somePatientFormJsp”;
}
}
Create the below Aspect for the annotation (RequiresRoles). You can use the same principle to create pointcuts for RequiresPermission.
import java.util.Arrays;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class WebAuthorizationAspect {
#Before("#target(org.springframework.stereotype.Controller) && #annotation(requiresRoles)")
public void assertAuthorized(JoinPoint jp, RequiresRoles requiresRoles) {
SecurityUtils.getSubject().checkRoles(Arrays.asList(requiresRoles.value()));
}
}
In your spring-webApplicationContext.xml wherever you have mentioned
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Annotation, so that it's easier to search controllers/components -->
<context:component-scan base-package="com.example.controller"/>
Note : The above two configuration should be placed together in the same spring-webApplicationContext.xml. Otherwise it won’t work. Moreover remove context:annotation-config if you have used it in your config. context:component-scan already scans all annotations.
If you're avoiding Spring XML and using primarily Java and annotation configuration, the easiest way to fix this is to add
#Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
to all your #Controller classes. You need cglib on the classpath.
I have only used spring-hibernate example from sample. To use annotations like #RequiresPermissions and others I tried configuration from shiro manual, configuration from this post, but I was either unsuccessful to compile or run the valid urls. So I only commented all the #RequiresPermissions from ManageUserController and started to use it in service implementation. E.g In DefaultUserService in getAllUsers method I added the annotation #RequiresPermissions("user:manage"). Magically now the application works as expected. Whenever the url manageUsers is called it displays the list page if the user has role user:manage and throws the user to /unauthorized if the user don't have that permission.
I have even configured the application to use mysql instead. To make the permissions independent of roles according to new RBAC(http://www.stormpath.com/blog/new-rbac-resource-based-access-control) I have created a new class called Permission as
#Entity
#Table(name = "permissions")
#Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class Permission {
#Id
#GeneratedValue
private Long id;
private String element;
private String description;
// setter and getter
Now Role class is configured as
#CollectionOfElements
#JoinTable(name="roles_permissions")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public Set<Permission> getPermissions() {
return permissions;
}
And finally SampleRealm as
for (Role role : user.getRoles()) {
info.addRole(role.getName());
System.out.println("Roles " + role.getName());
// Get permissions first
Set<Permission> permissions = role.getPermissions();
Set<String> permissionsStrings = new HashSet<String>();
for (Permission permission : permissions) {
permissionsStrings.add(permission.getelement());
System.out
.println("Permissions " + permission.getelement());
}
info.addStringPermissions(permissionsStrings);
}
It creates five tables as
| permissions |
| roles |
| roles_permissions |
| users |
| users_roles |
And permissions is independent of any other. According to new RBAC you have both ways (explicit and implicit) way of authorising resources.
You need to write the AuthorizationAttributeSourceAdvisor to enable Shiro's annotations bean as per the Shiro documentation
If you have written ShiroConfiguration class, make sure you include this:
#Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
#Bean
#ConditionalOnMissingBean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultSecurityManager securityManager) {
// This is to enable Shiro's security annotations
AuthorizationAttributeSourceAdvisor sourceAdvisor = new AuthorizationAttributeSourceAdvisor();
sourceAdvisor.setSecurityManager(securityManager);
return sourceAdvisor;
}
#ConditionalOnMissingBean
#Bean(name = "defaultAdvisorAutoProxyCreator")
#DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}
Example ShiroConfiguration on Github
I had the same problem. My fix was changing my jersey version from 2.2 to 2.22.2 and all #RequiresPermissions worked on my controllers.

Resources