Spring + Hibernate + DAO + SessionFactory + Inject - spring

I use Spring with Hibernate and get always a NPE for the sessionFactory Object.
My config file:
#Configuration
public class HibernateConfiguration {
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
Properties props = new Properties();
props.put("hibernate.dialect", MySQL5InnoDBDialect.class.getName());
props.put("hibernate.format_sql", "true");
props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
props.put("hibernate.connection.password", "xxx");
props.put("hibernate.connection.url", "jdbc:mysql://localhost/Market");
props.put("hibernate.connection.username", "philipp");
AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
bean.setAnnotatedClasses(new Class[] { xxx.class, xxx.class, xxx.class });
bean.setHibernateProperties(props);
bean.setSchemaUpdate(true);
return bean;
}
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(sessionFactory().getObject());
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
My DAOImpl class:
#Repository("xxx")
public class xxxDAOImpl implements xxxDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
...
Testcase:
#ContextConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
public class TestxxxDAOImpl {
#Test
#Transactional
public void testInsertxxx() throws Exception {
xxxDAO xxxDAO = new xxxDAOImpl();
xyz xyz = new xyz();
xxxDAO.insert(xyz);
assertNotNull(xyz.getId());
}
}
app-context.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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="xxx.config" />
<context:component-scan base-package="xxx.dao" />
<context:annotation-config></context:annotation-config>
test-context.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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<import resource="classpath:/META-INF/spring/app-context.xml" />
I get always an NPE from the currentSession when the test calls the insert method.
public void insert(xxx xxx) {
currentSession().save(xxx);
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}

The very first thing to understand when working with Spring is that Spring dependency injection only works for beans obtained from the application context, not for beans created with new.
In Spring-enabled unit tests you configure application context using #ContextConfiguration, for example, as follows (works in Spring 3.1, in previous versions #ContextConfiguration doesn't take #Configuration classes directly, therefore you'll have to create XML configuration file):
#Configuration
public class HibernateConfiguration {
// Add your DAO to application context
#Bean
public xxxDAO xxxDAO() {
return new xxxDAOImpl();
}
...
}
// Configure application context using the given #Configuration class
#ContextConfiguration(classes = HibernateConfiguration.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class TestxxxDAOImpl {
// Obtain DAO from the application context
#Autowired xxxDao xxxDao;
...
}

Instead of sessionFactory.getCurrentSession() in currentSession() function of xxxDAOImpl class, use sessionFactory.openSession().
Since in your first call there would not be any current session in the session factory so you need to open the session.
Hope this helps you. Cheers.

Related

Issue when executing spring bean

I've a bean named textFileWriter to write string entities to HDFS. I've configured the spring bean in bean config file. While executing am getting NullPointerException. Please help me on this.
My bean configuration :-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/hadoop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:hdp="http://www.springframework.org/schema/hadoop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">
<hdp:configuration id="hadoopConfigBean">
fs.defaultFS=${hdp.fs}
</hdp:configuration>
<beans:bean id="textFileWriter"
class="org.springframework.data.hadoop.store.output.TextFileWriter">
<beans:constructor-arg index="0" ref="hadoopConfigBean"></beans:constructor-arg>
<beans:constructor-arg index="1"
type="org.apache.hadoop.fs.Path" value="/user/mhduser"></beans:constructor-arg>
<beans:constructor-arg index="2" type="org.springframework.data.hadoop.store.codec.CodecInfo" >
<beans:null></beans:null>
</beans:constructor-arg>
</beans:bean>
<context:property-placeholder location="hadoop-configs.properties" />
</beans:beans>
Main Class :-
public class MainApp {
#Autowired
TextFileWriter textFileWriter;
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"/META-INF/spring/application-context.xml", MainApp.class);
System.out.println("Context loaded...");
MainApp obj=new MainApp();
obj.someMethod();
context.registerShutdownHook();
}
private void someMethod() {
try {
textFileWriter.write("hi there");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Am getting null pointer exception in this line :-
textFileWriter.write("hi there");
You can still make Spring inject dependencies without adding MainApp as a bean explicitly.
Enable annotation driven config. Add to the application-context.xml following
<context:annotation-config />
Make Spring wire dependencies with
MainApp obj=new MainApp();
context.getAutowireCapableBeanFactory().autowireBean(obj);
#Autowired won't work here because you are using a new instance of class MainApp which is not managed by spring and that's why you are getting a NullPointerException
MainApp obj=new MainApp();
obj.someMethod();
A work around would be :
public class MainApp {
public MainApp(TextFileWriter textFileWriter){
this.textFileWriter = textFileWriter;
}
public MainApp(){
}
#Autowired
TextFileWriter textFileWriter;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"/META-INF/spring/application-context.xml");
System.out.println("Context loaded...");
TextFileWriter textFileWriter = (TextFileWriter ) context.getBean("textFileWriter");
MainApp obj=new MainApp(textFileWriter );
obj.someMethod();
context.registerShutdownHook();
}
private void someMethod() {
try {
textFileWriter.write("hi there");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Spring JPA 2.0 Repository / Factory not working

I'm trying to implement a custom java Spring JPA repository, as described in the Spring documentation.
It seems that my spring config insists on creating the repositories in the standard way, instead of using the given MyRepositoryFactoryBean, giving me
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.myapp.repository.impl.DocumentRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1006)
... 43 more
Caused by: java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.<init>()
at java.lang.Class.getConstructor0(Class.java:2730)
at java.lang.Class.getDeclaredConstructor(Class.java:2004)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
I'm using Spring 3.2.2-RELEASE and spring-data-jpa-1.3.2-RELEASE, which is the latest if I'm correct. Here's my spring config:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<import resource="spring-repository-config.xml"/>
<import resource="spring-security-config.xml"/>
<context:component-scan base-package="com.myapp.web.controller"/>
<context:component-scan base-package="com.myapp.webservice.controller"/>
And here's the spring-repository-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd">
<repositories base-package="com.myapp.repository"
factory-class="com.myapp.repository.impl.MyRepositoryFactoryBean"/>
<!-- entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" -->
If've added debug breakpoints in all the methods of the com.myapp.repository.impl.MyRepositoryFactoryBean class, but these were not called.
The basic interface, just like in the example
package com.myapp.repository.impl;
#NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
The base implementation:
package com.myapp.repository.impl;
#NoRepositoryBean
public class MyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> {
private EntityManager entityManager;
public MyRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
super(domainClass, entityManager);
// This is the recommended method for accessing inherited class dependencies.
this.entityManager = entityManager;
}
public void sharedCustomMethod(ID id) {
// implementation goes here
}
}
And the factory:
package com.myapp.repository.impl;
import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new MyRepositoryFactory(entityManager);
}
private static class MyRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
private EntityManager entityManager;
public MyRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
return new MyRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
// The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
// to check for QueryDslJpaRepository's which is out of scope.
return MyRepositoryImpl.class;
}
}
}
My repositories interfaces are defines as:
package com.myapp.repository;
public interface DocumentRepository { // extends MyRepository<Document, Long>
public Document findByDocumentHash(String hashCode);
public Document findById(long id);
}
And the implementation is
package com.myapp.repository.impl;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class DocumentRepositoryImpl<Document, ID extends Serializable> extends MyRepositoryImpl<Document, Serializable> {
private static final long serialVersionUID = 1L;
public DocumentRepositoryImpl(Class<Document> domainClass, EntityManager entityManager) {
super(domainClass, entityManager);
}
And I use these repositories as autowired refernces in my controllers:
package com.myapp.web.controller;
#Controller
#RequestMapping(value = "/documents")
public class DocumentController {
#Autowired
private DocumentRepository documentRepository;
#RequestMapping(method = RequestMethod.GET)
public ModelAndView list(HttpServletRequest request) {
this.documentRepository. ...
}
I've looked at various resources on the web like this one, but I can't tell the difference with my code. Any hints are more than welcome!
You need default constructor for com.myapp.repository.impl.DocumentRepositoryImpl
public DocumentRepositoryImpl(){}
Spring first instantiate the beans that you declare in the app context (in your case) by calling the default constructor( no parameters ) and than uses setters to inject other beans.

Spring 3.2 AOP - Intercepting methods by annotation

I'm trying to intercept any method tagged w/ a custom annotation and the reason you read this is because I can't get it to work. I've been following simple examples but can't get it to work.
Here is my code.
MyAnnotation.java:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface MyAnnotation {
String value() default "";
String key() default "";
String condition() default "";
}
MyAspect.java:
#Aspect
public class MyAspect {
#Pointcut(value="execution(public * *(..))")
public void anyPublicMethod() { }
#Around("anyPublicMethod() && #annotation(myAnnotation)")
public Object process(ProceedingJoinPoint jointPoint, MyAnnotation myAnnotation) throws Throwable {
System.out.println("In AOP process");
return 5; //jointPoint.proceed();
}
}
spring-config.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
...
<context:component-scan base-package="com.myapp">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="myAspect" class="com.myapp.annotation.MyAspect" />
...
MyComponent.java:
#Component
public class MyComponent {
#MyAnnotation(value="valtest", key="keytest", condition="contest")
public int add(int i, int j) {
System.out.println("Executing annotation.add");
return i+j;
}
}
Test code:
final MyComponent m = new MyComponent();
assertTrue(5 == m.add(0, 1)); // Here m.add(...) always returns 1 instead of 5.
As a side note I've tried to define my pointcut many different ways, all with and without the use of the anyPublic() method and its execution pointcut, but none of those worked for me:
#Around("#annotation(com.myapp.annotation.MyAnnotation)")
public Object process(ProceedingJoinPoint jointPoint) throws Throwable { .. }
#Around(value="#annotation(myAnnotation)", argNames="myAnnotation")
public Object process(ProceedingJoinPoint jointPoint, MyAnnotation myAnnotation) throws Throwable { .. }
#Around("execution(* com.myapp.*.*(..)) && #annotation(com.myapp.annotation.MyAnnotation)")
public Object process(ProceedingJoinPoint jointPoint) throws Throwable { .. }
What am I doing wrong?
In your test code, you are not allowing Spring to create your MyComponent, but instead, you are using the new operator. You should be accessing MyComponent from Spring's ApplicationContext.
public class SomeTest {
public static void main(String[] args) throws Exception {
final ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
final MyComponent myComponent = appContext.getBean(MyComponent.class);
//your test here...
}
}
If you do not get your component from Spring, how do you expect it to be proxied?

My repository can't initialize automatically while using Spring Data JPA

I am trying to add spring data jpa to my spring-mvc web project after exploring a couple of tutorials. But I found my repository can't initialize automatically, I got NullPointerException in my service class. Please see my following sample code:
My repository:
public interface SubjectRepository extends JpaRepository<PSubject, String>{
public Page<PSubject> findByType(String title, Pageable pageable);
public Page<PSubject> findByType(String title);
public Page<PSubject> findByMacaddress(String macaddress, Pageable pageable);
public Page<PSubject> findByMacaddress(String macaddress);
public Page<PSubject> findByUri(String uri);
}
My controller:
#Controller
#RequestMapping("/subject")
public class VPSubjectController
{
....
#RequestMapping("/{id}.htm")
public ModelAndView detail(#PathVariable String id)
{
ModelAndView mav = new ModelAndView("subject/detail");
PSubject subject = subjectService.get(id);
....
}
}
My Service:
#Service("subjectService")
public class SubjectServiceImpl extends VPService implements SubjectService
{
#Autowired
private SubjectRepository subjectRepository;
......
#Override
#Transactional(propagation=Propagation.REQUIRED, readOnly=true)
public PSubject get(String subject) {
PSubject subObj = subjectRepository.findOne(subject);
return subObj;
}
.....
My configuration:
<?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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
....
<jpa:repositories base-package="com.mypacke.repository" repository-impl-postfix="Impl" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
....
I found in this line subjectRepository.findOne(subject) ,subjectRepository is null,
My question is similar this post
#Autowired annotation is activated by the statement:
<context:component-scan base-package="base.package"/>
If u do that, it would be initialized

How do I autowire a field when running Spring4JUnitRunner test?

I'm using Spring 3.1.0.RELEASE. I'm having trouble autowiring a private variable from a Spring4JUnitRunner class. My JUnit class is ...
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml" })
public class RegistrationControllerTest {
#Autowired
private ApplicationContext applicationContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private RegistrationController controller;
#Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
// I could get the controller from the context here
controller = new RegistrationController();
final RegistrationValidation registrationValidation = new RegistrationValidation();
controller.setRegistrationValidation(registrationValidation);
}
Not sure if its relevant, but here's my dispathcer-servlet.xml file ...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.myco.eventmaven" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/messages" />
</bean>
</beans>
Here is my controller. The "usersDao" field is null during my test, causing NullPointerExceptions (works fine when I run it as a normal webapp in JBoss) ...
#Controller
#RequestMapping("/registrationform.jsp")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
#Autowired
private RegistrationValidation registrationValidation;
#Autowired
private UsersDao usersDao;
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
LOG.debug("called GET method.");
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
// Process the form.
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(Registration registration, BindingResult result) throws NoSuchAlgorithmException, UnsupportedEncodingException {
String nextPage = "user/registrationform";
// set custom Validation by user
registrationValidation.validate(registration, result);
if (result.hasErrors()) {
return nextPage;
} else {
// Save the user to the database.
if (usersDao.saveUser(registration)) {
nextPage = "user/registrationsuccess";
} // if
} // if
return nextPage;
}
The class of the member field, usersDao, is annotated with the #Component annotation ...
#Component("usersDao")
public class UsersDaoImpl implements UsersDao {
What additional configuration do I need to add to properly autowire the dao object in my JUnit class? Thanks, -
You're getting the null because you're instantiating RegistrationController yourself, instead of getting the bean from Spring. You almost figured that out for yourself:
// I could get the controller from the context here
controller = new RegistrationController();
You could, and you should. Remove those two lines, and use the following on the field declartion:
#Autowired
private RegistrationController controller;

Resources