I am developing a primefaces - spring framework application but i have a big problem with my beans
i'm using spring annotations in java code to discover my beans, services, or component
but the problem is when i start jboss 7.1 AS and the beans are created i can see that my bean ListUsersBean
is created succesfully and the autowired setters are set successfully, but after when i try to invoke a test() method
from jsf page the autowired attributes are null.
I dont know what is happening
thanks a lot if anyone may help me
i'm using
spring-framework 3.2.2
JBOSS AS 7.1
primefaces 3.5
this is my bean
package edu.unbosque.beans;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedProperty;
import edu.unbosque.model.User;
import edu.unbosque.services.IUserService;
import edu.unbosque.services.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#ManagedBean
#SessionScoped
public class ListUsersBean implements Serializable{
/**
* Acceso A Datos De Usuario
*/
private IUserService userService;
private TestService testService;
/**
* Listado De Usuarios
*/
private List<User> usersList;
/**
* Usuario Seleccionado
*/
private User selectedUser;
/**
* Carga Los Usuarios
*/
private void populateUsers(){
this.usersList = this.userService.getUsers();
}
public IUserService getUserService() {
return userService;
}
#Autowired(required = true)
#Qualifier("userServiceImpl")
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public TestService getTestService() {
return testService;
}
#Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
public void test(){
this.testService = this.getTestService();
int i = 1;
i = i + 2;
}
}
this is my service
package edu.unbosque.services;
import java.util.List;
import javax.faces.bean.ManagedProperty;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import edu.unbosque.*;
import edu.unbosque.dao.UserDao;
import edu.unbosque.model.User;
import javax.inject.Named;
#Named("userServiceImpl")
public class UserServiceImpl implements IUserService{
#Autowired
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return (UserDetails) userDao.getUserByUserName(username);
}
#Override
public List<User> getUsers() {
return getUserDao().getUsers();
}
}
config files
faces-config.xml
*
<faces-config 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-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<lifecycle>
<phase-listener>edu.unbosque.listeners.LoginPhaseListener</phase-listener>
</lifecycle>
</faces-config>
*
spring-database.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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.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">
<context:annotation-config />
<context:component-scan base-package="edu.unbosque.model" />
<context:component-scan base-package="edu.unbosque.dao" />
<context:component-scan base-package="edu.unbosque.services" />
<context:component-scan base-package="edu.unbosque.beans" />
<context:property-placeholder location="classpath:jdbc.properties" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</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="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>edu.unbosque.model.User</value>
<value>edu.unbosque.model.Authority</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<display-name>Semilleros Universidad El Bosque</display-name>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
The problem is you are mixing up jsf, CDI and spring annotations. Use #Component in your class UserServiceImpl. Because if you use #Named, the created bean's life cycle will be managed by CDI, because its a CDi annotation. So as you are using #Autowired annotation to inject the bean, which is unknown to Spring, will get null. So as you are using #Autowired while injecting the bean, the injecting bean must be in spring managed context and to do that you should have use #Component. For further reading you can see this nice tutorial.
Related
UPDATE
Adding code in GameDetailImageMapper
package spring;
import entities.GameDetailImage;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class GameDetailImageMapper implements RowMapper
{
public GameDetailImage mapRow(ResultSet rs,int rowNum) throws SQLException
{
GameDetailImage gDetailImage = new GameDetailImage();
System.out.println("++++++++++++"+rs.toString());
gDetailImage.getGameDetail().setGameid( rs.getInt("game_id"));
gDetailImage.getGameDetail().setTitle( rs.getString("title"));
gDetailImage.getGameDetail().setDeveloper( rs.getString("developer"));
gDetailImage.getGameDetail().setPublisher( rs.getString("publisher"));
gDetailImage.getGameDetail().setGenre( rs.getString("genre"));
gDetailImage.getGameDetail().setPlatform( rs.getString("platform"));
gDetailImage.getGameDetail().setGameDescription( rs.getString("game_description"));
gDetailImage.getGameDetail().setDistribution( rs.getString("distribution"));
gDetailImage.getGameDetail().setReleaseDate( rs.getDate("release_date"));
gDetailImage.getGameDetail().setCreateDate( rs.getDate("create_date"));
gDetailImage.getGameDetail().setScore( rs.getInt("score"));
gDetailImage.getGameImage().setBanner_link( rs.getString("banner_link"));
gDetailImage.getGameImage().setBanner_title( rs.getString("banner_title"));
gDetailImage.getGameImage().setHero_link( rs.getString("hero_link"));
gDetailImage.getGameImage().setHero_title( rs.getString("hero_title"));
gDetailImage.getGameImage().setThumbnail_link( rs.getString("thumbnail_link"));
gDetailImage.getGameImage().setThumbnail_title( rs.getString("thumbnail_title"));
gDetailImage.getGameImage().setContent_image_link( rs.getString("content_image_link"));
gDetailImage.getGameImage().setContent_image_title( rs.getString("content_image_title"));
return gDetailImage;
}
}
Now that I have pointed my context config to the data.xml file I am getting the below exception. Not sure why this is happening as the query returns the correct data from my database. I am using a composite object in my mapper (two objects are included in the composite). Could that be what is causing the issue?
Stacktrace:] with root cause
java.lang.NullPointerException
at spring.GameDetailImageMapper.mapRow(GameDetailImageMapper.java:23)
at spring.GameDetailImageMapper.mapRow(GameDetailImageMapper.java:17)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:455)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:400)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
I am getting the following exception for my simple spring application. Think because I am not using spring injection correctly for the jdbcTemplate. I am using spring without Maven so no pom.xml. Running on Tomcat.
Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate spring.GameDetailImageManagement.jdbcTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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)}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<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>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
data.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/GameDisplay" />
<property name="username" value= />
<property name="password" value= />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg type="javax.sql.DataSource" name="dataSource" ref="dataSource"/>
</bean>
<context:annotation-config />
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<!--Handle #Autowired-->
<context:annotation-config />
</beans>
`GameDetailImageController:
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import spring.GameDetailImageManagement;
#Controller
public class GameDetailImageController
{
#Autowired
private GameDetailImageManagement gdm;
#RequestMapping("/index")
protected ModelAndView listGameDetailImages
(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView("index");
//ModelAndView mv = new ModelAndView("index", "gameDetailImages", dao.GameDetailImageDAO.getGameDetailImages());
mv.addObject("gameDetailImages", gdm.getGameDetailImages());
return mv;
}
}
GameDetailImageManagement
package spring;
import entities.GameDetailImage;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class GameDetailImageManagement
{
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource)
{
this.jdbcTemplate.setDataSource(dataSource);
}
/*public void setJdbcTemplate(JdbcTemplate template)
{
this.jdbcTemplate = template;
}*/
public List getGameDetailImages()
{
//List templist;
//templist = jdbcTemplate.query("select * from GameDetail Inner Join GameImage on GameDetail.game_id = GameImage.game_id Order By GameDetail.create_date", new GameDetailImageMapper());
//System.out.println("++++===++++"+templist.toString());
return this.jdbcTemplate.query("select * from GameDetail Inner Join GameImage on GameDetail.game_id = GameImage.game_id Order By GameDetail.create_date", new GameDetailImageMapper());
}
}
Thanks pointing the config file to my data.xml was the first step. The next step was that I wasn't using the mapper correctly. I added the getters and setters directly to the GameDetailImageMapper without using getGameDetail() and getGameImage().
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/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Self Service Portal</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>login</filter-name>
<filter-class>com.app.api.filter.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Spring Context Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
</web-app>
Custom filter class:-
package com.app.api.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebFilter("/*")
public class AuthenticationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
public AuthenticationFilter() {
System.out.println("Authentication - default filter !");
}
public void destroy() {
System.out.println("Authentication - destroy !");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
LOGGER.debug("Request authentication!");
HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
if(uri.equals("/app-api/login") || uri.equals("/app-api/logout")) {
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if(session == null || session.getAttribute("user") == null) {
writeInvalidCredentialResponse((HttpServletResponse) response);
} else {
chain.doFilter(request, response);
}
}
private void writeInvalidCredentialResponse(HttpServletResponse response) throws IOException {
Map<String, String> errorResponse = new HashMap<String, String>();
errorResponse.put("message", "Please login with right credentials!");
ObjectMapper mapper = new ObjectMapper();
String responseMessage = mapper.writeValueAsString(errorResponse);
LOGGER.debug("Invalid request authentication!");
LOGGER.debug(responseMessage);
response.getWriter().write(responseMessage);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Authentication - init !");
}
}
Project hierarchy:-
A - parent maven module
B - RESTful webservices sub module (contains - /WEB-INF/web.xml, /WEB-INF/dispatcher-servlet.xml)
C - persistence layer sub module (contains - /resources/applicationContext.xml, /resources/persistence.xml)
Please help me to resolve this issue to make my both spring context up and running (ui - webservices and persistence)
Many thanks in advance !
app-api
/app-api/src/main/webapp/WEB-INF/dispatcher-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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="classpath:/applicationContext-data.xml" />
<context:annotation-config />
<context:component-scan base-package="com.app" />
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven/>
</beans>
app-data
/app-data/src/main/resources/applicationContext-data.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- ************* JPA/Hibernate configuration ************* -->
<bean
name="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.data.*" />
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="persistence-unit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/app"
p:username="root"
p:password="root123"
p:initialSize="5"
p:maxActive="10">
</bean>
<context:component-scan base-package="com.app.data.*" />
<tx:annotation-driven />
</beans>
Let's see the exception:
java.lang.ClassNotFoundException: com.adobe.ssp.api.filter.AuthenticationFilter
There was a problem with your classpath, the class "com.adobe.ssp.api.filter.AuthenticationFilter" was not found. Please make sure this class is contained in: YOUR_APP\WEB-INF\classes or YOUR_APP\WEB-INF\lib
Try removing #WebFilter and make sure about your init method overriding as we can't see that in code provided.
I am using pure xml in spring configuration. I have applicationContext.xml and servletContext.xml. In applicationContext.xml, I created the dao and service bean while in servletContext.xml, I created controller bean that references the service bean in applicationContext. Then in controller class, I have this code to initialize the bean
private PersonService personService
public void setPersonService(PersonService personService){
this.personService = personService;
}
When I call method in personService, Im getting a null pointer exception. I guess that the service bean is null. What am I doing wrong?
This is my beans xml
applicationContext.xml
<bean id="personDao" class="com.training.hibernate.dao.impl.PersonDaoImpl">
<constructor-arg>
<ref bean="sessionFactory"/>
</constructor-arg>
</bean>
<bean id="personService" class="com.training.hibernate.services.impl.PersonServiceImpl">
<constructor-arg>
<ref bean="personDao"/>
</constructor-arg>
</bean>
servletContext.xml
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="com.training.hibernate.controller.PersonController">
<property name="personService" ref="personService"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
This is my controller
public class PersonController extends MultiActionController {
private PersonService personService;
public void setPersonService(PersonService PersonService){
this.personService = personService;
}
public ModelAndView getAllPersons(HttpServletRequest request, HttpServletResponse response) throws Exception{
List<PersonDto> personDtos = personService.getAllPersons();
ModelAndView model = new ModelAndView("index");
model.addObject("persons",personDtos);
model.addObject("roles",personService.getRoles());
return model;
}
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
ModelAndView model = new ModelAndView("person");
return model;
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Spring Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servletContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
Following is the code and I have already inserted data in database using BCrypt password encoder. While inserting I did BCrypt in java code. I am adding Spring Security to my project. As a first stage, I have added BCrypt to my spring-security.xml and I try to log in and I debug the code and I see "Bad Credentials Exception"
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml,
/WEB-INF/spring/appServlet/spring-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/spring-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:b="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:security="http://www.springframework.org/schema/security"
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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<b:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
<security:authentication-manager >
<security:authentication-provider user-service-ref="personService">
<security:password-encoder ref="encoder"/>
</security:authentication-provider>
</security:authentication-manager>
<security:global-method-security secured-annotations="enabled"/>
<b:bean id="personDAO" class="com.cT.www.dao.PersonDAOImpl">
<b:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</b:bean>
<!-- For hashing and salting user passwords -->
<b:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<b:bean id="personService" class="com.cT.www.service.PersonServiceImpl">
<b:property name="personDAO" ref="personDAO"></b:property>
</b:bean>
<security:http use-expressions='true'>
<security:form-login login-page="/login" default-target-url="/loginSuccess"
authentication-failure-url="/home"
username-parameter="mobile_Number"
password-parameter="password"/>
<security:intercept-url pattern="/home" access="permitAll" />
<security:intercept-url pattern="/RankOption/**" access="hasRole('ROLE_ADMIN')" />
<security:logout logout-url="/logout"/>
</security:http>
<b:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<b:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<b:property name="url"
value="jdbc:mysql://121.0.0.1:3306/testDB" />
<b:property name="username" value="root" />
<b:property name="password" value="" />
</b:bean>
<!-- Form Validator -->
<b:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<b:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</b:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<b:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<b:property name="dataSource" ref="dataSource" />
<b:property name="packagesToScan">
<b:list>
<b:value>com.cT.www.model</b:value>
</b:list>
</b:property>
<b:property name="hibernateProperties">
<b:props>
<b:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</b:prop>
<b:prop key="hibernate.show_sql">true</b:prop>
</b:props>
</b:property>
</b:bean>
<context:component-scan base-package="com.cT.www" />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<b:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<b:property name="prefix" value="/WEB-INF/views/" />
<b:property name="suffix" value=".jsp" />
</b:bean>
</b:beans>
PersonServiceImpl.java
package com.cT.www.service;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cT.www.dao.PersonDAO;
import com.cT.www.model.Best_Option_Questions;
import com.cT.www.model.Options;
import com.cT.www.model.Person;
import com.cT.www.model.Questions;
import com.cT.www.model.Rank_Option_Questions;
import com.cT.www.model.Reset_Password;
import com.cT.www.model.UserSignUp;
import com.cT.www.model.UserVerification;
import com.cT.www.model.Yes_Or_No;
#Service
public class PersonServiceImpl implements PersonService, UserDetailsService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Override
#Transactional
public List getMobile_Number_N_Password(String mobile_Number) {
// TODO Auto-generated method stub
return this.personDAO.getMobile_Number_N_Password(mobile_Number);
}
#Override
#Transactional
public UserDetails loadUserByUsername(String mobile_Number)
throws UsernameNotFoundException {
// TODO Auto-generated method stub
// return this.getMobile_Number_N_Password(Long.parseLong(mobile_Number));
List result = personDAO.getMobile_Number_N_Password(mobile_Number);
String existing_Password = null;
Boolean verification_Boolean = false;
if(result != null){
if(result.get(0) != null){
for(Iterator itr = result.iterator(); itr.hasNext();){
Object[] myResult = (Object[]) itr.next();
existing_Password = (String) myResult[0];
verification_Boolean = (Boolean) myResult[1];
}
}
}
if(result == null){
throw new UsernameNotFoundException("No user found with mobile number" + mobile_Number);
}
return new org.springframework.security.core.userdetails.User(mobile_Number,
existing_Password,true, true, true, true, getGrantedAuthorities());
}
private List<GrantedAuthority> getGrantedAuthorities(){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("VERIFIED_USER"));
return authorities;
}
}
I am trying to implement a spring security in my project my requirements are
First user will login with url that will generate a secuirty code -
http://localhost:8181/SpringSecurity/login
After successfully loggedIn I hit secuired API call like -
http://localhost:8181/SpringSecurity/admin with secured key generated by login method
I am using crome postman to hit APIs
Although I am loggedIn with a user having ROLE_ADMIN but still it is not allow me to access secured APIs
my web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
servlet-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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ha.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="targetUrl" />
</bean>
<context:component-scan base-package="com.ha.**" />
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="../spring-security.xml"/>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<security:global-method-security secured-annotations="enabled"/>
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<custom-filter ref="tokenProcessingFilter" after="FORM_LOGIN_FILTER" />
</http>
<beans:bean
class="com.ha.security.AuthenticationTokenAndSessionProcessingFilter"
id="tokenProcessingFilter">
<beans:constructor-arg name="principal" value="ANONYMOUS" />
<beans:constructor-arg name="authority" value="anonymousUser" />
<beans:constructor-arg name="tokenStore" ref="inMemoryTokenStore" />
</beans:bean>
<beans:bean class="com.ha.security.InMemoryTokenStore" id="inMemoryTokenStore" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="hr" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller file is
package com.ha.security;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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 org.springframework.web.bind.annotation.ResponseStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ha.model.UserEntity;
import com.ha.services.IUserService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
private InMemoryTokenStore tokenStore;
#Autowired
IUserService userServices;
/* #RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String welcomePage() {
return "index";
} */
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
#Secured("ROLE_ADMIN")
public #ResponseBody String defaultPage() {
List<UserEntity> userEntity = userServices.getUsersList();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.toJson(userEntity);
}
#RequestMapping(value = "/admin", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto adminPage() {
return new ResponseDto("Can Access Admin");
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto login(#RequestBody UserLoginDto loginDto) {
String userName = loginDto.getUserName();
String password = loginDto.getPassword();
if (StringUtils.hasText(userName) && StringUtils.hasText(password)
&& userServices.validateAdminUser(loginDto)) {
ArrayList<GrantedAuthority> objAuthorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority objAuthority = new SimpleGrantedAuthority(
"ROLE_ADMIN");
objAuthorities.add(objAuthority);
User user = new User(userName, password, objAuthorities);
return new ResponseDto(this.tokenStore.generateAccessToken(user));
} else {
return new ResponseDto("Not Valid User");
}
}
}
AuthenticationTokenAndSessionProcessingFilter
package com.ha.security;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
public class AuthenticationTokenAndSessionProcessingFilter extends
GenericFilterBean {
private final InMemoryTokenStore tokenStore;
private final Object principal;
private final List<GrantedAuthority> authorities;
public AuthenticationTokenAndSessionProcessingFilter(
InMemoryTokenStore tokenStore, String authority, String principal) {
this.tokenStore = tokenStore;
this.principal = principal;
this.authorities = AuthorityUtils.createAuthorityList(authority);
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting a HTTP request");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = null;
UserDetails objUserDetails = null;
if (StringUtils.hasText(httpRequest.getHeader("Authorization"))) {
authToken = httpRequest.getHeader("Authorization");
objUserDetails = this.tokenStore
.readAccessToken(authToken);
}
setAuthentication(objUserDetails, httpRequest);
chain.doFilter(request, response);
}
private void setAuthentication(UserDetails objUserDetails,
HttpServletRequest request) {
UsernamePasswordAuthenticationToken authentication = null;
if (null != objUserDetails) {
authentication = new UsernamePasswordAuthenticationToken(
objUserDetails, null, objUserDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(request));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
} else {
authentication = new UsernamePasswordAuthenticationToken(
this.principal, null, this.authorities);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
}
}
}
I believe you need to use hasRole method
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
And also I noticed that you have only one user in your users list with role "ROLE_USER" hope you have added the admin user as well.
Thanks for your support, Problem get solved now and It was with importing style of security action. I was importing securty xml file multiple times
I had import securty in
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
as well as in spring-context.xml file
<import resource="../spring-security.xml"/>
due to that multiple instances creted of inMemoryTokenStore and while validating it checking user token with different one.
After removed entry from spring-context.xml and adding following qualifer in HomeController my code is working fine
#Qualifier("inMemoryTokenStore")
private InMemoryTokenStore tokenStore;
Thanks evertybuddy....:)