Spring MVC Autowired null in Component - spring

My component is:
package com.netpc.recruitment.models.user;
#Component
public class UserAuth {
#Autowired
private HttpSession httpSession;
#Autowired
private IUserDAO userDAO;
}
Vars httpSession and userDAO, while creating object in controllers, are null. userDAO is configured properly and it works fine in my com.netpc.recruitment.controllers.IndexController class #Controller.
My web.xml
<beans ......>
<context:component-scan base-package="com.netpc.recruitment.controllers" />
<bean id="userDAO" class="com.netpc.recruitment.models.user.JDBCUserDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Whats wrong with it? Why it's null?

Your component scan is scanning only on "com.netpc.recruitment.controllers". Should also scan in package com.netpc.recruitment.models.user. Changes in web.xml:
<context:component-scan base-package="com.netpc.recruitment.controllers" />
to this:
<context:component-scan base-package="com.netpc.recruitment.controllers, com.netpc.recruitment.models.user" />
Hope this works for you!

Related

Spring Autowiring not working - BeanCreationException

I want to integrate Spring with Hibernate. I am new to both technologies. At the moment I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserService controller.HomeController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Can anybody help me, please?
package controller;
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping("/register")
public ModelAndView getRegisterForm(#ModelAttribute("user") User user,
BindingResult result) {
ArrayList<String> gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");
ArrayList<String> city = new ArrayList<String>();
city.add("Delhi");
city.add("Kolkata");
city.add("Chennai");
city.add("Bangalore");
Map<String, Object> model = new HashMap<String, Object>();
model.put("gender", gender);
model.put("city", city);
System.out.println("Register Form");
return new ModelAndView("Register", "model", model);
}
#RequestMapping("/saveUser")
public ModelAndView saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
System.out.println("Save User Data");
return new ModelAndView("redirect:/userList.html");
}
#RequestMapping("/userList")
public ModelAndView getUserList() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", userService.getUser());
return new ModelAndView("UserDetails", model);
}
}
package service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void addUser(User user) {
userDao.saveUser(user);
}
#Override
public List<User> getUser() {
return userDao.getUser();
}
}
spring-servlet Code:
Hi need a Spring ,Hibernate integration example for my new project.so i have copied this from a website.and i did some modifications in that ..It's not working please help me
<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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="controller" />
<tx:annotation-driven/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="myydao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="/user/*.htm" class="controller.HomeController" >
<property name="UserDao" ref="mydao" />
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume that you haven't added the bean to your Spring Application Context
If you are using xml, you need to do this by adding something like the following to the xml file:
<bean class="service.UserServiceImpl" id="userService"/>
Or, if you are using a Java based configuration class, you need to add a bean like so:
#Configuration
public class AppConfig{
#Bean
public UserService userService() {
return new UserServiceImpl();
}
}
Or, if you add the #Component annotation to UserServiceImpl and #ComponentScan("service") annotation to the Java App config, it should pick up the User service
Make sure you have enabled the component scanning to automatically detect classes and register respective beans.
You should add below entry to your bean definition XML file:
<context:component-scan base-package="org.example"/>
More about automatic bean detection

Mixing declarative beans and annotated beans: org.hibernate.HibernateException No Session found for current thread

I get "No Session found for current thread".
I suppose the problem is in mixing declarative xml beans and annotated beans.
Following, I'll resume my config.
MyLibrary Project
Spring 3.1.4
Hibernate 4
applicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan
base-package="com.mycompany.dao.core, com.mycompany.services.core,
com.mycompany.permissionEvaluator" />
<import resource="model-core-security.xml" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
... (sessionFactory ecc...)
model-core-security.xml
<bean id="expressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator" />
</bean>
<security:global-method-security
pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler" />
</security:global-method-security>
With component-scan I create beans: AccountService, AccountDAO and PermissionEvaluator.
AccountService.java (com.mycompany.services)
#Service("accountService")
#Transactional
public class AccountServiceImpl implements AccountService {
#Resource
private AccountDAO accountDAO;
...
}
AccountDAO.java (com.mycompany.dao)
#Repository
#Transactional
public class HibernateAccountDAOImpl implements AccountDAO {
...query...
}
(AccountService e AccountDAO are transactional)
Now, within AccountController.java I call accountService.listAccounts() and it's all right!
But, if I inject AccountService into PermissionEvaluator class (following snippet), AccountController gets No Session found for current thread when invokes accountService.listAccounts()
PermissionEvaluator.java (com.mycompany.permissionEvaluator)
Component("permissionEvaluator")
public class PermissionEvaluatorImpl implements PermissionEvaluator {
#Resource
private AccountService accountService;
...
}
I use PermissionEvaluator (with AccountService, AccountDAO) created by component-scan in expressionHandler bean declared in model-core-security.xml.
Might it be the cause of "no session found for currend thread"?
#Transactional
what's ur import package
import org.springframework.transaction.annotation.Transactional; ??
U can try to import "import javax.transaction.Transactional;"

Injecting EntityManager using Spring ( Null Pointer Exception ) [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
Here's the code insidy my ApplicationContext.xml
<context:spring-configured />
<context:annotation-config />
<context:component-scan base-package="com.apsas.jpa" />
<tx:annotation-driven />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="testjpa" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
and here's my Dao Implementation
public class TeacherDaoImpl implements TeacherDao {
#Autowired
private EntityManager entityManager;
#Transactional
public Teacher addTeacher(Teacher teacher) {
entityManager.persist(teacher);
return teacher;
}
}
Here's my Main Class
public class TestApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"config/ApplicationContext.xml");
TeacherDao teacherDao = new TeacherDaoImpl();
Teacher teacher1 = teacherDao.addTeacher(new Teacher("First Teacher"));
}
}
Please help, i am getting a null pointer exception
Exception in thread "main" java.lang.NullPointerException
at com.apsas.jpa.dao.impl.TeacherDaoImpl.addTeacher(TeacherDaoImpl.java:22)
at com.apsas.jpa.main.TestApp.main(TestApp.java:26)
ive been solving this problem in 2 days but still i cant find any resources that may solve this problem. i appreciate if you give me your opinion,answers or any idea that might help me solving this,
ps: i am new on learning spring
Since you are instantiating TeacherDaoImpl yourself (with the new keyword) within main, Spring is not injecting the EntityManager and hence the NPE.
Annotate the field TeacherDaoImpl.entityManager with #PersistenceContext and annotate the TeacherDaoImpl class with #Component to have Spring instantiate it for you. Then in your main, get a hold of that bean:
TeacherDao dao = applicationContext.getBean(TeacherDao.class);
// ...
Also these two directives seem to be unnecessary:
<context:annotation-config />
<context:spring-configured />
The former is implied when you are using <context:component-scan />. The latter is only useful if you are using #Configurable in your code.
You will want to use #PersistenceContext for injecting the EntityManager.
See
PersistenceContext EntityManager injection NullPointerException
which is pretty much the same question.

spring el not working with #Transactional

faces-config.xml
- org.springframework.web.jsf.DelegatingVariableResolver
applicationContext.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<context:component-scan base-package="com.test"/>
index.xhtml
<h:outputText value="#{authBean.val}"/>
AuthBean.java
package com.test.ui;
#Component
#Scope("session")
public class AuthBean {
#Getter #Setter private String val;
#Transactional public void test(){} //works fine if #Transactional is removed
Works fine,but when a method is annotated with #Transactional,the below error occurs
16:23:13,906 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/jbtst].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: javax.el.PropertyNotFoundException: /index.xhtml #14,49 value="#{authBean.val}": The class '$Proxy28' does not have the property 'val'.
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:111) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIOutput.getValue(UIOutput.java:169) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
Using spring-3.1, hibernate3
When you use #Transactional Spring creates a proxy that implements the same interface as your class, but your AuthBean class doesn't implement an interface.
The easiest way to fix this would be to define an interface with the val property and have AuthBean implement that interface, the proxy will then also have the val property.
This helps annotation equivalent of <aop:scoped-proxy>
<context:component-scan base-package="com.test" scoped-proxy="targetClass" />

Spring + TestNG integration tests, injecting DAO with annotations fails

I first did not mention what was the key component of this issue: I am using TestNG here.
I have a DAO layer performing persistence. It works fine as part of my little web app (I have a classic Controller, Service, DAO layers design). I can update this question with my XMLs if required.
My Service layer
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
public GoodVibeUserDetails getUser(String username) throws UsernameNotFoundException {
GoodVibeUserDetails user = userDao.getDetailsRolesAndImagesForUser(username);
return user;
}
// more methods...
}
My DAO layer
#Repository
public class UserDaoImplHibernate implements UserDao {
#Autowired
private SessionFactory sessionFactory;
// My methods using sessionFactory & "talking" to the Db via the sessionFactory
}
And here is my Test Class
#Component
public class UserDaoImplHibernateTests{
#Autowired
private UserDao userDao;
private GoodVibeUserDetails user;
#BeforeMethod
public void beforeEachMethod() throws ParseException{
user = new GoodVibeUserDetails();
user.setUsername("adrien");
user.setActive(true);
// & so on...
}
/*
* When everything is fine - test cases
*/
#Test
public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
assertNotNull(userDao) ;
user = userDao.registerUser(user);
assertNotNull(user.getId()) ;
}
// more test cases...
}
But for my test class the Autowiring, userDao always returns Null, I'm only starting to do tests in Spring and I'm a bit lost. Any pointers are welcome.
Latest edit after Boris Treukhov's answer
import ...
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.junit.Assert.assertNotNull;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/applicationContext.xml")
public class UserDaoImplHibernateTests{
#Autowired
#Qualifier("userDao")
private UserDao userDao;
private GoodVibeUserDetails user;
#BeforeMethod
public void beforeEachMethod() throws ParseException{
user = new GoodVibeUserDetails();
user.setUsername("adrien");
user.setActive(true);
// & so on...
}
/*
* When everything is fine - test cases
*/
#Test
public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
assertNotNull(userDao) ;
user = userDao.registerUser(user);
assertNotNull(user.getId()) ;
}
// more test methods...
}
And this is my 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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" >
<!-- the application context definition scans within the base package of the application -->
<!-- for #Components, #Controller, #Service, #Configuration, etc. -->
<context:annotation-config />
<context:component-scan base-package="com.goodvibes" />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
<prop key="hibernate.connection.SetBigStringTryClob">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
[...]
</beans>
I did not add a repository-config.xml as this should be enough to access userDao. I still get userDao equal null though.
Thanks in advance
If you create unit tests, Spring IoC functionality is unavailable(as it was intended by the framework designers), because you are testing your objects in isolation(i.e. you are mocking only minimal set of interfaces which are required for the test to complete). In this case you should inject your mock repository manually, for example in #Before test initialization method. The whole idea is that your classes only depend on interfaces, so basically Spring container evaluates which class to use as the interface implementation, but when you create a unit test you need to have a strict control of which interface methods were called(and have a minimal set of dependencies), that is why you perform the injection manually.
If you are doing integration testing, you should have a Spring IoC container instance up and running, for this to work you should use jUnit(assuming that you are using jUnit) specific test runner, as it described in the Spring documentation on testing.
So, returning to the question, you have what looks like a simple unit test to jUnit, and the Spring container is not used. So, if you are going to use Spring TestContext framework, you should have something like
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"/path-to-app-config.xml", "/your-test-specific-config.xml"})
public class UserDaoImplHibernateTests
instead of #Component.
update in TestNg case I think it should be (I used Spring Dependency Injection with TestNG as the reference)
#ContextConfiguration(locations={"/path-to-app-config.xml", "/your-test-specific-config.xml"})
public class UserDaoImplHibernateTests extends AbstractTestNGSpringContextTests
See also: What is the difference between integration and unit tests?

Resources