Spring MVC Custom Converter for JSON data not working - java

I am creating a test application to to achieve conversion from JSON String to Employee Object before being passed to the controller.
Here are the key steps performed
Creation of Employee.java Class : Domain Object
Creation of EmployeeManagementController.java class : Spring MVC Controller for Managing Employee
Creation of EmployeeConverter.java : Custom Converter for Converting JSON String to Employee Object.
Creation of employee-servlet.xml : Spring Configuration file
Creation of web.xml : The Deployment Descriptor
Employee.java
package com.bluebench.training.domain;
import org.springframework.stereotype.Component;
#Component("employee")
public class Employee {
private PersonalDetail personal;
private EducationDetail education;
private WorkExperienceDetail experience;
// Getters and Setters
}
other domain objects are also defined
EmployeeManagementController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bluebench.training.domain.Employee;
#Controller
public class EmployeeManagementController {
#RequestMapping(value="/ems/add/employee",method=RequestMethod.POST,consumes="application/json",produces="application/json")
public #ResponseBody int addEmployee(#RequestBody Employee emp){
System.out.println("RAGHAVE");
System.out.println(emp.getPersonal().getName());
int empId = 20;
return empId;
}
}
EmployeeConverter.java
package com.bluebench.training.converter;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.convert.converter.Converter;
import com.bluebench.training.domain.Employee;
public class EmployeeConverter implements Converter<String,Employee>{
#Override
public Employee convert(String json) {
System.out.println("Inside convert()");
Employee emp = null;
try {
emp = new ObjectMapper().readValue(json,Employee.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return emp;
}
}
employee-servlet.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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.bluebench.training"/>
<mvc:annotation-driven conversion-service="conversionService"/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="defaultContentType" value="text/html"/>
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.bluebench.training.converter.EmployeeConverter"/>
</list>
</property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>PROJECT_38_SpringMVCRESTFul</display-name>
<servlet>
<servlet-name>employee</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>employee</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/employee-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
I am using Firefox RestClient to Test it.
Here is the JSON which correctly maps to the Employee object.
{"personal":{"name":"Raghave","age":33,"phoneNumber":"9594511111","address":"101, software appartment, software land , mumbai"},"education":{"qualifications":[{"insititute":"Amity University","degree":"Bachelor of Science","yearOfPassing":"2007","percentage":62.0}]},"experience":{"experience":[{"companyName":"QTBM","designation":"Programmer","years":3,"salary":12000.0},{"companyName":"Polaris","designation":"Software Developer","years":1,"salary":24000.0},{"companyName":"Ness","designation":"Senior Software Engineer","years":2,"salary":50000.0},{"companyName":"JPMC","designation":"Senior Applications Developer","years":1,"salary":120000.0}]}}
There is no Exception thrown and the controller does receive the Employee Object in the addEmployee() method. But its not via converter. The Converter is not invoked. I dont know why ? I dont want to use init binders or #Valid. I wanted to know where am i going wrong. how to make it work?

You've confused Spring's general type conversion support that uses Converters and the ConversionService with its support for HTTP message conversion that is specifically designed for converting web requests and responses and understands media types (like application/json that you're using). HTTP message conversion uses instance of HttpMessageConverter.
You don't actually need a custom converter in this case. Spring's MappingJacksonHttpMessageConverter is being used to perform the conversion automatically. The conversion can be performed automatically because, presumably (you haven't posted the setters so I'm making an educated guess), the setter methods in Employee match the JSON, i.e. setName, setAge, setPhoneNumber etc.
Arguably, the code that you've got is already working. You can safely delete your custom converter, have the same functionality, and have less code to maintain. If you really want to use a custom converter, you'll need to implement HttpMessageConverter and configure it before/in place of MappingJacksonHttpMessageConverter.

Related

Unable to apply aspects to String class

I was experimenting with AspectJ. I tried to apply aspect on String class. I created Spring configuration file as:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- Enable #AspectJ annotation support -->
<aop:aspectj-autoproxy />
<!-- Employee manager -->
<bean id="employeeManager" class="com.test.advice.EmployeeManager" />
<!-- Logging Aspect -->
<bean id="loggingAspect" class="com.test.advice.LoggingAspect" />
<bean id="bean1" class="java.lang.String">
<constructor-arg value="abx" />
</bean>
</beans>
Then an Aspect class like,
package com.test.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
#Aspect
public class LoggingAspect
{
#Around("execution(* java.lang.String.*(..))")
public void logAroundGetEmployee(ProceedingJoinPoint joinPoint) throws Throwable
{
System.out.println("works");
}
}
After that created a class with a main method like:
package com.test.advice;
package com.test.advice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectJAutoProxyTest
{
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Customer.xml");
String pqr = (String) context.getBean("bean1");
pqr.trim();
}
}
On running it should output "works" to console. But it fails saying,
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy5 cannot be cast to java.lang.String
at com.test.advice.AspectJAutoProxyTest.main(AspectJAutoProxyTest.java:13)
What is the issue? Can't we apply proxy to java.lang objects? Please help.
To use a proxy object as a replacement for the real object, the proxy object must be of a subclass of the real object. String being final, the JVM does not permit creating such a subclass.
(Note that spring has two proxy modes; one creates an actual subclass and the other just implements all public interfaces. You're probably using the latter, but if you changed to the former, you'd see an exception at proxy creation time)

Spring AOP Advice is being executed twice

I am using Spring AOP to create an Aspect. The Aspect that I defined is being executed twice. I can't seem to figure out why. I'd appreciate any inputs anyone has on this issue.
Thanks!
// Spring 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:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.xsd"
default-autowire="no"
default-lazy-init="true">
<bean id="loggingAdvice" class="com.xyz.aop.LoggingAdvice" />
<aop:config>
<aop:aspect id="loggingAspect" ref="loggingAdvice">
<aop:pointcut id="loggingPointcut"
expression="execution(* com.xyz.FooServiceImpl.foo(..))"/>
<aop:around pointcut-ref="loggingPointcut" method="log" />
</aop:aspect>
</aop:config>
<context:component-scan base-package="com.xyz.controllers" />
</beans>
// Advice
package com.xyz.aop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
public class LoggingAdvice {
public Object log(final ProceedingJoinPoint pjp) throws Throwable {
log.info("Started!");
try {
return pjp.proceed();
} finally {
log.info("Ended!");
}
}
}
// Advised Method
package com.xyz;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FooServiceImpl implements FooService {
private static final Log log = LogFactory.getLog(FooServiceImpl.class);
#Override
public void foo() {
log.info("Foo!");
}
}
}
// Output
Started!
Started!
Foo!
Ended!
Ended!
// EDIT 1: Added more spring configuration info. Not using any Spring AOP annotations at all. I attached a debugger and saw that the aspect/log statements were being executed twice as well. So I doubt that it has anything to do with log statement printing the string twice.
Well, it seems like this is actually an issue with the logger. Same problem I encountered long time back and found that everything is being logged twice. When I replaced logger calls with regular sysout calls, everything worked fine.
Because the <aop:around...> is telling this to do work both before and after the method. You could use <aop:before...> or <aop:after...> instead for running only once.

Load Time Weaving not working in domain object

I have a scenario where I need to access spring managed beans in my domain object(i.e. object created with new operator). I searched a lot and found that it can be done using Load Time Weaving provided by aspectJ. I've done all configurations for the above to the best of my knowledge. I'm new to aspectJ. Following are my code and the configuration files.
Domain class,
package test.components;
import hibSERVICES.NounHeader.NounHeaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
#Configurable
public class TestLoadTimeWeaving {
#Autowired
private NounHeaderService nounHeaderService;
public void hello(){
nounHeaderService.findByPrimaryKey(0L);
}
}
Controller,
package test.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/testController.do")
public class TestController{
#RequestMapping(params = "todo=onLoad", method = {RequestMethod.POST, RequestMethod.GET})
public void onLoad(HttpServletRequest request, HttpServletResponse response){
TestLoadTimeWeaving testLoadTimeWeaving = new TestLoadTimeWeaving();
testLoadTimeWeaving.hello();
}
}
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:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:spring-configured />
<context:annotation-config />
<context:component-scan base-package="test" />
<context:load-time-weaver aspectj-weaving="on"/>
<bean lass="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect" factory-method="aspectOf"/>
aop.xml,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN"
"http://www.aspectj.org/dtd/aspectj_1_5_0.dtd">
<aspectj>
<weaver>
<exclude within="*..*CGLIB*" />
</weaver>
</aspectj>
I've written -javaagent:c:\spring-agent-2.5.6.jar as the VM argument
Using following jars to support LTW and aspectJ,
aspectjrt-1.5.4.jar
spring-agent-2.5.6.jar
spring-aspect.jar
aspectjWeaver-1.5.4.jar
spring-2.5.6.jar
All other spring dependencies are working fine, only the dependencies which are injected in the domain objects( i.e. object created with new operator) are not working i.e. I'm getting null for those depedencies.
Kindly help. Thanks in advance.

Spring WS + JIBX "No adapter for endpoint" Error

I use JIBX to create my entity classes from XSD files. It is configured in pom.xml and creates classes when I do a "maven: compile"
I also use spring-ws. When I test my web service with SOAPUI I get the infamous error;
"No adapter for endpoint GetTransactionsResponse getTransactions(GetTransactionsRequest), Is your endpoint annotated with #Endpoint, or does.."
I checked all the threads here about that error but didn't help.
I have one Parent.xsd and it imports 2 child xsd's. They are all in the same folder. This is how my spring-ws-servlet looks like;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean name="xsdCollection" class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
<property name="xsds">
<list>
<value>/WEB-INF/Parent.xsd</value>
</list>
</property>
</bean>
<context:component-scan base-package="mypackage"/>
<sws:annotation-driven/>
<sws:dynamic-wsdl id="my" portTypeName="myResource" locationUri="/ws/my"
targetNamespace="myschame">
<sws:xsd location="/WEB-INF/Parent.xsd"/>
</sws:dynamic-wsdl>
<sws:interceptors>
<bean class="org.springframework.ws.soap.server.endpoint.interceptor.SoapEnvelopeLoggingInterceptor">
<property name="logRequest" value="true"/>
<property name="logResponse" value="true"/>
</bean>
<bean class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<property name="xsdSchemaCollection" ref="xsdCollection"/>
<property name="validateRequest" value="true"/>
<property name="validateResponse" value="true"/>
</bean>
</sws:interceptors>
This is my endpoint class;
#Endpoint
public class TransactionsEndpoint {
public static final String NAMESPACE = "nmapespace";
#PayloadRoot(namespace = NAMESPACE, localPart = "getTransactionsRequest")
#ResponsePayload
public GetTransactionsResponse getTransactions(#RequestPayload GetTransactionsRequest request) {
GetTransactionsResponse transactionsResponse = new GetTransactionsResponse();
return transactionsResponse;
}
}
GetTransactionsResponse/Request classes created by JIBX.
My wsdl looks like this;
<wsdl:operation name="getTransactions"><wsdl:input message="tns:getTransactionsRequest" name="getTransactionsRequest">
</wsdl:input><wsdl:output message="tns:getTransactionsResponse" name="getTransactionsResponse">
</wsdl:output></wsdl:operation>
pom file is;
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.xmlschema</groupId>
<artifactId>xmlschema-core</artifactId>
<version>2.0.2</version>
</dependency>
I am not sure if the problem is because there are 3 xsd files and something goes wrong between those or it is a configuration problem with JIBX because When I try to use JAXB instead of JIBX, it worked!
Endpoint mappings are stored in a hashmap with a key based on the namespace and the local part of the #PayloadRoot annotation (see code below). You currently have (what I assume is) a typo in the namespace of the java class... nmapespace instead of namespace.
If this does not match up with what is located in your xsd and subsequently published wsdl (which are not shown), then the mapping would not be found. This is one (of the many) possible reasons that you would get that error.
public class PayloadRootAnnotationMethodEndpointMapping extends
AbstractAnnotationMethodEndpointMapping<QName> {
...
#Override
protected QName getLookupKeyForMethod(Method method) {
PayloadRoot annotation = AnnotationUtils.findAnnotation(method, PayloadRoot.class);
if (annotation != null) {
QName qname;
if (StringUtils.hasLength(annotation.localPart()) && StringUtils.hasLength(annotation.namespace())) {
qname = new QName(annotation.namespace(), annotation.localPart());
}
else {
qname = new QName(annotation.localPart());
}
return qname;
}
else {
return null;
}
}
If this is not the problem, you may need to add some more info to the question (soap request, xsds, wsdl).
I also had similar issue(spent several days) however in my case issue being Spring WS and Spring versions being incompatible, check whether your Spring WS and Spring versions match.

Problems using Hibernate and Spring in Wicket

I'm writing a little web-interface for a database I created. The database access is done through Hibernate, but it also uses Spring for injecting instances of DAO's (which in turn have a SessionFactory injected). I test the web-interface on an embedded Jetty server. Everything works fine when used independently: I can get stuff out of the database from the database project, I can run a webpage using Wicket on the Jetty server, I even managed to get Spring working for the WicketTester, which was a bit of a pain in the ass. But now when I try to get something out of the database (by clicking some button on the webpage), I get an error saying:
java.lang.NullPointerException
at nl.ru.cmbi.pdbeter.core.controller.DAO.GenericDAO.getCurrentSession(GenericDAO.java:37)
Somehow the sessionFactory that should have been injected in the DAO wasn't injected. I defined the DAO bean in applicationContext.xml of the Wicket module, but I assumed that as soon as it would see the #Autowired of the SessionFactory it would look in the spring.xml file of thát project, but apparently it doesn't. I'll put some code below to show the individual parts at work.
The WicketApplication:
#Service
public class WicketApplication extends WebApplication {
#SpringBean
private IPDBEntryDAO pdbEntryDAO;
public IPDBEntryDAO getPdbEntryDAO() {
return pdbEntryDAO;
}
public void setPdbEntryDAO(IPDBEntryDAO pdbEntryDAO) {
this.pdbEntryDAO = pdbEntryDAO;
}
/**
* #see org.apache.wicket.Application#getHomePage()
*/
#Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
/**
* #see org.apache.wicket.Application#init()
*/
#Override
public void init() {
super.init();
new ClassPathXmlApplicationContext("applicationContext.xml").getAutowireCapableBeanFactory().autowireBean(this);
}
public void setupInjector() {
getComponentInstantiationListeners().add(new SpringComponentInjector(this));
}
}
The class which starts the embedded Jetty server (copied from the Wicket quickstart):
public class Start {
public static void main(String[] args) throws Exception {
int timeout = (int) Duration.ONE_HOUR.getMilliseconds();
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(timeout);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.addConnector(connector);
// check if a keystore for a SSL certificate is available, and
// if so, start a SSL connector on port 8443. By default, the
// quickstart comes with a Apache Wicket Quickstart Certificate
// that expires about half way september 2021. Do not use this
// certificate anywhere important as the passwords are available
// in the source.
Resource keystore = Resource.newClassPathResource("/keystore");
if (keystore != null && keystore.exists()) {
connector.setConfidentialPort(8443);
SslContextFactory factory = new SslContextFactory();
factory.setKeyStoreResource(keystore);
factory.setKeyStorePassword("wicket");
factory.setTrustStoreResource(keystore);
factory.setKeyManagerPassword("wicket");
SslSocketConnector sslConnector = new SslSocketConnector(factory);
sslConnector.setMaxIdleTime(timeout);
sslConnector.setPort(8443);
sslConnector.setAcceptors(4);
server.addConnector(sslConnector);
System.out.println("SSL access to the quickstart has been enabled on port 8443");
System.out.println("You can access the application using SSL on https://localhost:8443");
System.out.println();
}
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
// START JMX SERVER
// MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
// server.getContainer().addEventListener(mBeanContainer);
// mBeanContainer.start();
server.setHandler(bb);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
The web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>web-interface</display-name>
<!--
There are three means to configure Wickets configuration mode and they
are tested in the order given.
1) A system property: -Dwicket.configuration
2) servlet specific <init-param>
3) context specific <context-param>
The value might be either "development" (reloading when templates change) or
"deployment". If no configuration is found, "development" is the default. -->
<filter>
<filter-name>wicket.web-interface</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>nl.ru.cmbi.pdbeter.WicketApplication</param-value>
</init-param>
<init-param>
<param-name>applicationFactoryClassName</param-name>
<param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
</init-param>
<init-param>
<param-name>applicationBean</param-name>
<param-value>wicketApplication</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>wicket.web-interface</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The SpringWebApplicationFactory will need access to a Spring Application context, configured like this... -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
The applicationContext.xml file:
<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"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<!--
<context:component-scan base-package="nl.ru.cmbi.pdbeter" />
-->
<!-- setup wicket application -->
<bean id="wicketApplication" class="nl.ru.cmbi.pdbeter.WicketApplication">
<property name="pdbEntryDAO" ref="pdbEntryDAO"/>
</bean>
<bean id="pdbEntryDAO" class="nl.ru.cmbi.pdbeter.core.controller.DAO.PDBEntryDAO" />
</beans>
Part of the DAO class from the database module:
public class GenericDAO<I> implements IGenericDAO<I> {
private Class<I> persistentClass;
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public GenericDAO() {
persistentClass = (Class<I>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
The spring.xml file used by the database module:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="nl.ru.cmbi.pdbeter" />
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<!-- Session Factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="hibernate.cfg.xml" />
<property name="packagesToScan" value="nl.ru.cmbi.pdbeter.core.model.domain" />
</bean>
</beans>
Sorry for posting so much code, but I think I might let important stuff out if I don't.
Does anyone know how to make sure everything gets injected, both for the Wicket module as for the database module?

Categories