Autowiring not working after adding spring security - spring

I'm working on a spring project and I'm trying to apply sprin security.The problem is that when I add spring-security.xml at contextConfigurationLocation parameters for some reason I can't figure out service beans are not autowired at controllers and I get
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.ibios.services.ArticleCategoryService] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:952)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:821)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4149)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4458)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
spring security xml file is:
<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:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<debug/>
<http pattern="/resources" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/logout" access="permitAll"/>
<intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/user" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>
<form-login login-page="/login"
authentication-failure-url="/login/failure"
default-target-url="/"/>
<access-denied-handler error-page="/denied"/>
<logout invalidate-session="true"
logout-success-url="/logout/success"
logout-url="/logout"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
</authentication-provider>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>
root-context xml is:
<?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:project.properties" />
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:/META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="entityManager" />
<property name="dataSource" ref="datasource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="terminologyService" class="com.ibios.services.impl.TerminologyServiceImpl" />
<bean id="articleCategoryService" class="com.ibios.services.impl.ArticleCategoryServiceImpl" />
<bean id="exerciseCategoryService" class="com.ibios.services.impl.ExerciseCategoryServiceImpl"/>
<bean id="exerciseService" class="com.ibios.services.impl.ExerciseServiceImpl"/>
<bean id="articleService" class="com.ibios.services.impl.ArticleServiceImpl"/>
<bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<jpa:repositories base-package="com.ibios.repositories" />
<context:component-scan base-package="com.ibios.web" />
</beans>
articleCategory service impl class is:
public class ArticleCategoryServiceImpl implements ArticleCategoryService{
#Resource
ArticleCategoryRepository articleCategoryRepository;
#Override
public void create(ArticleCategory articleCategory) {
articleCategoryRepository.saveAndFlush(articleCategory);
}
#Override
public void update(ArticleCategory articleCategory) {
articleCategoryRepository.saveAndFlush(articleCategory);
}
#Override
public void delete(ArticleCategory articleCategory) {
articleCategoryRepository.delete(articleCategory);
}
#Transactional
#Override
public List<ArticleCategory> findAll() {
List<ArticleCategory> articleCategories = articleCategoryRepository.findAll();
return articleCategories;
}
#Override
public Page<ArticleCategory> findAll(Pageable pageable) {
PageRequest page1 = new PageRequest(pageable.getPageNumber(),
pageable.getPageSize(), Direction.DESC, "id");
Page<ArticleCategory> categories = articleCategoryRepository.findAll(page1);
return categories;
}
#Override
public ArticleCategory getById(Integer id) {
ArticleCategory articleCategory = articleCategoryRepository.findOne(id);
return articleCategory;
}
#Override
public List<ArticleCategory> findLatest() {
List<ArticleCategory> latest=articleCategoryRepository.findLatest();
return latest;
}
}
and the controller class is
#Controller
public class AddArticleCategoryController {
#Autowired
private ArticleCategoryService articleCategoryService;
#RequestMapping(value = "/addArticleCategory", method = RequestMethod.POST)
public String addArticleCategory(#ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
articleCategory.setCreated(Calendar.getInstance());
articleCategoryService.create(articleCategory);
return "addArticleCategory";
}
#RequestMapping(value = "/addArticleCategory", method = RequestMethod.GET)
public ModelAndView showrticleCategory(#ModelAttribute ArticleCategory articleCategory, BindingResult result) {
return new ModelAndView("addArticleCategory", "articleCategory", new ArticleCategory());
}
#RequestMapping(value = "/showArticleCategories", method = RequestMethod.GET)
public String showArticleCategories(Model model, #PageableDefaults(pageNumber = 0, value = 15) Pageable pageable) {
Page<ArticleCategory> page = articleCategoryService.findAll(pageable);
model.addAttribute("page", page);
return "showArticleCategories";
}
#RequestMapping(value = "/editArticleCategory", method = RequestMethod.GET)
public String editArticleCategory(#RequestParam("id") String id, Model model) {
ArticleCategory articleCategory = articleCategoryService.getById(Integer.parseInt(id));
model.addAttribute("articleCategory", articleCategory);
return "editArticleCategory";
}
#RequestMapping(value = "/editArticleCategory", method = RequestMethod.POST)
public String editArticleCategorires(#ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
System.out.println("CREATED:" + (String) result.getFieldValue("created"));
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date createdDate = formatter.parse((String) result.getFieldValue("created"));
Calendar created = Calendar.getInstance();
created.setTime(createdDate);
articleCategory.setCreated(created);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
articleCategoryService.update(articleCategory);
return "showArticleCategories";
}
public ArticleCategoryService getArticleCategoryService() {
return articleCategoryService;
}
public void setArticleCategoryService(ArticleCategoryService articleCategoryService) {
this.articleCategoryService = articleCategoryService;
}
}
the web.xml part for spring security is:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
<param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<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>
Up until now I've tried to use ArticleCategoryService interface instead of the implementing class,I've set proxy-target-class to "true" at the transaction manager all of them with no results.

Try to add the #Service annotation to the ArticleCategoryServiceImpl
Change your web.xml from
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
<param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>
To:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml</param-value>
</context-param>

Related

Don't work #autowire in Spring

I want to autowire my userService, but I'm getting an error. I have:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.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>*.htm</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<context:annotation-config/>
<context:component-scan base-package="com.andrylat.rgz.ocean.controllers" />
<context:component-scan base-package="com.andrylat.rgz.ocean.services" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<tx:annotation-driven />
application-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.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.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- DataAccess -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="user" value="rgz1002"/>
<property name="password" value="aqweds"/>
</bean>
<context:component-scan base-package="com.andrylat.rgz.ocean.dao"/>
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.andrylat.rgz.ocean.domains</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.andrylat.rgz.ocean.domains"/>
<bean id="userDAO" class="com.andrylat.rgz.ocean.dao.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userService"
class="com.andrylat.rgz.ocean.services.UserService">
<property name="userDAO" ref="userDAO" />
</bean>
<bean id="userServiceForSecurity"
class="com.andrylat.rgz.ocean.services.UserService">
<property name="userDAO" ref="userDAO" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.andrylat.rgz.ocean.services.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
<!-- Spring Security -->
<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
</bean>
<sec:http auto-config="true" use-expressions="true">
<!--access-denied-handler error-page="/403" /-->
<sec:logout logout-success-url="/index.htm" />
<sec:form-login login-page="/login.htm"
default-target-url="/Ocean/test/testpage.htm"
authentication-failure-url="/login.htm?error=1" />
<sec:intercept-url pattern="/test/*"
access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
<sec:intercept-url pattern="/*"
access="permitAll" />
<sec:intercept-url pattern="/resources/**"
access="permitAll" />
<sec:csrf />
</sec:http>
<!--sec:authentication-manager>
<sec:authentication-provider>
<sec:jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select login, password, enabled from users where login =? "
authorities-by-username-query=
"select login, userrole from userroles where login =? " />
<sec:password-encoder ref="passwordEncoder" />
</sec:authentication-provider>
</sec:authentication-manager-->
<sec:authentication-manager>
<sec:authentication-provider user-service-ref="userServiceForSecurity" >
<sec:password-encoder ref="passwordEncoder" />
</sec:authentication-provider>
</sec:authentication-manager>
UserService.java
#Service("userService") public class UserService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Transactional(readOnly = true)
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
com.andrylat.rgz.ocean.domains.User user = userDAO.findByUserName(username);
List<GrantedAuthority> authorities
= new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(user.getRole ()));
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(com.andrylat.rgz.ocean.domains.User user,
List<GrantedAuthority> authorities) {
return new User(user.getLogin(), user.getPassword(),
user.getEnabled(), true, true, true, authorities);
}}
IndexController.java
#Controller public class IndexController {
//#Autowired
//#Qualifier("userService")
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Autowired
private SessionFactory sessionFactory;
#RequestMapping (value="/index", method=RequestMethod.GET)
private ModelAndView getIndexPage (){
if (sessionFactory==null) {
System.err.println("sessionFactory is null!");
} else {
System.err.println("sessionFactory OK!");
}
return new ModelAndView ("index");
}
#RequestMapping (value="/login", method=RequestMethod.GET)
private ModelAndView getLoginPage (){
return new ModelAndView ("login");
} }
Problem: my UserService in IndexController.java don't autowired! And i was added "sessionFactory" and it don't autowired too. "SessionFactory" is only null and when i write annotation to UserService i have next stacktrace (from jsp):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.andrylat.rgz.ocean.services.UserService com.andrylat.rgz.ocean.controllers.IndexController.userService; nested exception is java.lang.IllegalArgumentException: **Can not set com.andrylat.rgz.ocean.services.UserService field com.andrylat.rgz.ocean.controllers.IndexController.userService to com.sun.proxy.$Proxy158**
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
I don't understand why I can't get this UserService and my sessionFactory is null.
Seems like the problem with the application-context.xml naming.
So, Ensure that the file applicationContext.xml exists with proper name (should not be application-context.xml) in the WEB-INF folder so that the sessionFactory bean will be loaded. Otherwise, the sessionFactory bean object will be null.
Error was in
private UserService userService;
UserService is class and not interface. I create interface UserServiceI (UserService is implement UserServiceI) and write in IndexController
#Autowire
private UserServiceI userService;
All works!

#Autowired not working in AuthenticationSuccessHandler of Spring-Security

Hi I am unable to access spring bean in AuthenticationSuccessHandler of spring security.I saw many post in stackoverflow but no luck nothing works,
Spring-MVC-3.2.6
Spring Security - 3.2.0
Please find the below file for reference,
servlet-config.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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
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-3.2.xsd">
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<context:component-scan base-package="com.taskmanagement" />
<security:global-method-security
pre-post-annotations="enabled">
<!--register security:expression-handler To use rights(hasPermission) along
wih roles(hasRole) -->
<security:expression-handler ref="TaskManagementExpressionHandler" />
</security:global-method-security>
<bean id="TaskManagementExpressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator">
<bean id="permissionEvaluator"
class="com.taskmanagement.security.TaskManagementPermissionEvaluator">
<property name="dataSource" ref="dataSource"></property>
</bean>
</property>
</bean>
<!--mvc:resources is used for static file location location is a folder
underneath spring will look for static resources 2)Also we should configure
this in web.xml.Because right now we configured only for .html not .pdf -->
<mvc:resources location="pdfs" mapping="/pdfs/**" />
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:resources mapping="/webjars/**" location="/webjars/"/>
<!-- p:basename :: Here we should give the property file name here the name
is messages. This bean is simply used by spring for message resource -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages" />
<!--This bean is simply used by spring for message resource for locale resolver
it uses interceptor -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
p:defaultLocale="en" />
<!-- Now register locale interceptor.That's it for locale -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="language"></bean>
</mvc:interceptors>
<import resource="hibernate-config.xml" />
<!-- Method1 Long hand <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix"
value=".jsp"></property> </bean> -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="3"></bean>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
p:order="2" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean
class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="applicaton/json"></entry>
<entry key="xml" value="applicaton/xml"></entry>
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"></property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"></property>
<property name="order" value="0"></property>
</bean>
<!-- Helper class to configure Tiles 2.x for the Spring Framework -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/tiles2/TilesConfigurer.html -->
<!-- The actual tiles templates are in the tiles-definitions.xml -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/config/tiles-definitions.xml</value>
</list>
</property>
</bean>
<import resource="classpath:/WEB-INF/config/security-config.xml" />
</beans>
security-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- We are making security as default bean instead of beans -->
<beans:beans 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:p="http://www.springframework.org/schema/p" xmlns="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
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-3.2.xsd">
<!-- This will activate the expressions in spring valid expr are : hasRole,hasAnyRole,hasPermission,PermitAll -->
<http use-expressions="true" auto-config="true">
<!-- Allow login only user must have ROLE_USER -->
<!-- The below line is for spring basic authentication without using custom
controller * jsp <http-basic/> -->
<!-- For custom login use the below code -->
<intercept-url pattern="/login*" access="permitAll" /> <!-- Without this it won't allow the access for login.html because in the
above we restrained URL with ROLE_USER -->
<intercept-url pattern="/resources/**" access="permitAll"/>
<intercept-url pattern="/loginFailed.html" access="permitAll" />
<intercept-url pattern="/logout.html" access="permitAll" />
<intercept-url pattern="/signup.html" access="permitAll" />
<intercept-url pattern="/signupSubmit.html" access="permitAll" />
<intercept-url pattern="/session-expired.html" access="permitAll" />
<intercept-url pattern="/updatepassword*" access="permitAll"/>
<intercept-url pattern="/changePassword*" access="permitAll"/>
<intercept-url pattern="/403.html" access="permitAll" />
<!--<intercept-url pattern="/**" access="ROLE_USER"/> if we activate expression
then we should use hasRole or hasAnyRole or hasPermission or PermitAll in
access other wise it ill throw http status 500 failed to evaluate expr error -->
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.html"
authentication-failure-url="/loginFailed.html" authentication-success-handler-ref="successAuthenticationHandler"/>
<logout logout-success-url="/logout.html" delete-cookies="JSESSIONID"/>
<access-denied-handler error-page="/403.html" />
<remember-me key="myAppKey" user-service-ref="userDetailsService"/>
<!-- This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated.
Often you would prefer to prevent a second login, in which case you can use -->
<session-management invalid-session-url="/session-expired.html">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/session-expired.html"/>
</session-management>
</http>
<!-- Password Hashing Bean -->
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" >
<beans:constructor-arg name="strength" value="12" />
</beans:bean>
<!-- After successfull login using the below handler we will map to corresponding screen -->
<beans:bean id="successAuthenticationHandler"
class="com.taskmanagement.authentication.handler.SuccessAuthenticationHandler"/>
<authentication-manager>
<!-- <authentication-provider user-service-ref="userDetailsService"/> -->
<authentication-provider>
<!-- The below code will configure md5 <password-encoder hash="md5"></password-encoder> -->
<!-- The below code will configure bcrypt -->
<password-encoder ref="passwordEncoder"></password-encoder>
<!--<jdbc-user-service data-source-ref="dataSource" /> -->
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,password, enabled from users where username=?"
authorities-by-username-query="select username, authority from authorities where username =? " />
</authentication-provider>
</authentication-manager>
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/taskmgmt"></beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="root"></beans:property>
</beans:bean>
<beans:bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
<!-- Session Timeout & Concurrency control -->
</beans:beans>
SuccessAuthenticationHandler.java
package com.taskmanagement.authentication.handler;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import com.taskmanagement.dao.CommonDao;
#Service("authenticationSuccessHandler")
public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
private CommonDao userDao;
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
System.out.println("onAuthenticationSuccess::Entered");
User user = (User)authentication.getPrincipal();
String userName = user.getUsername();
System.out.println("userName::"+user.getUsername());
com.taskmanagement.model.User userBo = this.userDao.get(com.taskmanagement.model.User.class,userName);
userBo.setLastLogggedIn(new Date());
userDao.saveOrUpdate(user);
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/** Builds the target URL according to the logic defined in the main class Javadoc. */
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
System.out.println("isUser::"+isUser+"::isAdmin::"+isAdmin);
if (isUser) {
return "/adminEntryAction.html";
} else if (isAdmin) {
return "/addMinutes.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
In SuccessAuthenticationHandler.java while accessing this.userDao it throws nullPointerException could anyone please guide me to resolve this issue.
Kindly let me know for any queries.
CommonDao.java
public interface CommonDao {
public <T> Integer save(final T obj);
public <T> String saveRetString(final T obj);
public <T> void delete(final Class<T> type,final String obj);
public <T> T get(final Class<T> type, final String id);
public <T> T merge(final T o);
public <T> void saveOrUpdate(final T o);
public <T> List<T> getAll(final Class<T> type);
public List<UserBO> searchContacts(String name);
}
CommonDaoImpl.java
#Repository
public class CommonDaoImpl implements CommonDao {
#Autowired
HibernateSessionFactory hibernateSessionFactory;
#SuppressWarnings("unchecked")
public <T> Integer save(final T obj){
//interact wth DB
}
public <T> String saveRetString(final T obj){
//interact wth DB
}
public <T> void delete(final Class<T> type,final String id){
//interact wth DB
}
#SuppressWarnings("unchecked")
public <T> T get(final Class<T> type, final String id){
return (T) hibernateSessionFactory.getSession().get(type, id);
}
#SuppressWarnings("unchecked")
public <T> T merge(final T o){
//interact wth DB
}
/***/
public <T> void saveOrUpdate(final T o){
//interact wth DB
}
#SuppressWarnings("unchecked")
public <T> List<T> getAll(final Class<T> type) {
//interact wth DB
}
#SuppressWarnings("unchecked")
#Override
public List<UserBO> searchContacts(String name) {
//interact wth DB
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<!-- It is need for spring security to intercept URL -->
<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> <!-- We are going to send every rquest to this filter -->
</filter-mapping>
<!-- It will tell where the spring security configuration xml is -->
<!-- Bootstraps the root web application context before servlet initialization -->
<!-- It will bootstrap our spring security -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
<servlet>
<servlet-name>taskManagementServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>taskManagementServlet</servlet-name>
<url-pattern>/pdfs/**</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout> <!-- THis specify timeout in minutes -->
</session-config>
<display-name>Archetype Created Web Application</display-name>
</web-app>
After added the following load on startup(refer below code),
<servlet>
<servlet-name>taskManagementServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Getting the following exception,
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765) [catalina.jar:7.0.23]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260) [catalina.jar:7.0.23]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.23]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525) [catalina.jar:7.0.23]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515) [catalina.jar:7.0.23]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_18]
at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_18]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_18]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_18]
at java.lang.Thread.run(Thread.java:619) [na:1.6.0_18]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
... 22 common frames omitted
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
... 22 more
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/TaskManagement] startup failed due to previous errors
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

Spring security SessionRegistry not working

First of all I kept the listener in web.xml
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
Then my springSecurity.xml goes like
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/*" access="permitAll" />
<security:session-management invalid-session-url="/" session-fixation-protection="newSession">
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" session-registry-alias="sessionRegistry"/>
</security:session-management>
<!-- access denied page -->
<security:access-denied-handler error-page="/loginerror" />
<security:form-login
login-page="/login?login_error=1"
default-target-url="/employee/listEmployee"
authentication-failure-url="/login/error"
/>
<security:logout invalidate-session="true" logout-success-url="/login" delete-cookies="JSESSIONID" />
<!-- enable csrf protection -->
<!-- <csrf/>-->
</security:http>
<!-- Select users and user_roles from database -->
<security:authentication-manager>
<security:authentication-provider ref="authenticationProvider"></security:authentication-provider>
</security:authentication-manager>
<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService">
<bean id="userAuthenticationService" class="com.elitenet.los.security.UserDetailsServiceImpl" />
</property>
<property name="passwordEncoder">
<bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" />
</property>
</bean>
The controller goes like:I need the list of userNames which are logged in. But the sessionRegistry isn't working.
#Autowired
#Qualifier("sessionRegistry")
private SessionRegistry sessionRegistry;
#RequestMapping(value = "/showUserStatus",method = RequestMethod.GET)
public ModelAndView showUserStatus() {
List<String> usersNamesList = new ArrayList<String>();
List<User> userList = new ArrayList<User>();
try {
List<Object> principals =sessionRegistry.getAllPrincipals();//the principals here is empty
for (Object principal: principals) {
//import org.springframework.security.core.userdetails for User class
//User is a built in class of spring security core
if (principal instanceof User) {
getLog().info(((User) principal).getUserName());
getLog().info("going to list userNameList");
usersNamesList.add(((User) principal).getUserName());
}
}
getLog().info("going to list user");
userList = getUserService().getList();
} catch (Exception er) {
getLog().error("error while listing userList" + er);
}
return new ModelAndView("/user/showUserStatus", "userList", userList);
}
Can anyone help me what am I doing wrong
Please try mentioning in xml file
<bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
#Controller class
Try injecting like below
#Resource(name="sessionRegistry")
private SessionRegistryImpl sessionRegistry;
I think you are almost there. The only thing you've probably missed is the use of session-registry-alias. By using that attribute on the concurrency-control element you expose the session registry, so that it can be injected to your own beans.
Now you have a reference to the session registry that will be populated by the ConcurrentSessionControlStrategy which is set up implicitly by the above configuration. To use it you would just inject it to your bean as normal:
<security:session-management>
<security:concurrency-control max-sessions="10" session-registry-ref="sessionRegistry"/>
</security:session-management>
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
or something like below
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy"
p:maximumSessions="1" >
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
</bean>

Autowire doesnt work in custom UserDetailsService

In my custom user details service, my variable "aUserService" doesnt auto wire even already annotated. tried a lot method, but still failed and the value is null.
Acutally i follow from krams tutorial.
http://krams915.blogspot.sg/2012/01/spring-security-31-implement_1244.html
here is my project https://skydrive.live.com/#cid=837EF1FA9A4C06AE&id=837EF1FA9A4C06AE%21130 ,enviroment: netbeans 7.2,maven,tomcat 7.0.39,postgresql 9.2,db sql inside the project. db pool defined at META-INF/context.xml
here is my
web.xml
<?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">
<filter>
<filter-name>setEncoding</filter-name>
<filter-class>sg.com.innovax.opscentralv5.objects.setEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>setEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- ================================ START Captha ================================ -->
<filter>
<filter-name>jcaptchaFilter</filter-name>
<filter-class>sg.com.innovax.jcaptcha.JCaptchaFilter</filter-class>
<init-param>
<param-name>failureUrl</param-name>
<param-value>/?error=true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jcaptchaFilter</filter-name>
<url-pattern>/jcaptcha.jpg</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>jcaptchaFilter</filter-name>
<url-pattern>/j_spring_security_check</url-pattern>
</filter-mapping>
<!-- ================================ END Captha ================================ -->
<!-- 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>
<!-- 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
/WEB-INF/spring/security.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>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<error-page>
<error-code>401</error-code>
<location>/WEB-INF/views/401.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/views/403.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/500.jsp</location>
</error-page>
<resource-ref>
<description>postgreSQL</description>
<res-ref-name>jdbc/postgres</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- solr server url -->
<context-param>
<param-name>solr_url</param-name>
<param-value>http://localhost:8080/solr</param-value>
</context-param>
</web-app>
my spring servlet xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
my security xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<debug />
<global-method-security pre-post-annotations="enabled"/>
<http pattern="/resources/**" security="none"/>
<http pattern="/test/**" security="none"/>
<http pattern="/loggedout.jsp" security="none"/>
<http pattern="/forgotPassword" security="none"/>
<http pattern="/ProcessResetPassword" security="none"/>
<http pattern="/test" security="none"/>
<http pattern="/jcaptcha.jpg" security="none"/>
<http use-expressions="true">
<intercept-url pattern="/" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-processing-url="/j_spring_security_check"
login-page="/"
default-target-url="/user/"
always-use-default-target="true"
authentication-failure-url="/?error=true" />
<remember-me key="OpsCentral" token-validity-seconds="3600"/>
<logout logout-url="/j_spring_security_logout" />
</http>
<context:annotation-config />
<context:component-scan base-package="sg.com.innovax" />
<authentication-manager >
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="sha"/>
</authentication-provider>
</authentication-manager>
<!-- Jcaptcha -->
<beans:bean id="captchaService"
class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">
<beans:property name="captchaEngine">
<beans:bean class="sg.com.innovax.jcaptcha.GMailEngine" />
</beans:property>
<!-- 180 secs to expired
<property name="minGuarantedStorageDelayInSeconds" value="180" />
-->
</beans:bean>
</beans:beans>
my root-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:jee="http://www.springframework.org/schema/jee"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
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.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
">
<context:annotation-config />
<context:component-scan base-package="sg.com.innovax" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Root Context: defines shared resources visible to all other web components -->
<jee:jndi-lookup id="dataSource"
jndi-name="jdbc/postgres"
expected-type="javax.sql.DataSource" />
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<beans:property name="defaultLocale" value="en" />
</beans:bean>
<!-- Register the welcome.properties -->
<beans:bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="welcome" />
</beans:bean>
<!-- JPA -->
<beans:bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="database" value="POSTGRESQL" />
</beans:bean>
</beans:property>
<beans:property name="packagesToScan" value="sg.com.innovax" />
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="100000000"/>
</beans:bean>
my custom user detail service
package sg.com.innovax.opscentralv5.objects;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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 sg.com.innovax.opscentralv5.table.service.UserService;
/**
* A custom {#link UserDetailsService} where user information
* is retrieved from a JPA repository
*/
#Service
#Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserService aUserService;
/**
* Returns a populated {#link UserDetails} object.
* The username is first retrieved from the database and then mapped to
* a {#link UserDetails} object.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
sg.com.innovax.opscentralv5.table.User u = aUserService.findByUsername(username);
String pass = sg.com.innovax.opscentralv5.table.User.byteToHex(u.getPassword());
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
u.getUsername(),
pass,
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(1));
} catch (Exception e) {
System.out.println(e.toString());
throw new RuntimeException(e);
}
}
/**
* Retrieves a collection of {#link GrantedAuthority} based on a numerical role
* #param role the numerical role
* #return a collection of {#link GrantedAuthority
*/
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
/**
* Converts a numerical role to an equivalent list of roles
* #param role the numerical role
* #return list of roles as as a list of {#link String}
*/
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 1) {
roles.add("ROLE_USER");
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 2) {
roles.add("ROLE_USER");
}
return roles;
}
/**
* Wraps {#link String} roles to {#link SimpleGrantedAuthority} objects
* #param roles {#link String} of roles
* #return list of granted authorities
*/
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
my user service implement
package sg.com.innovax.opscentralv5.table.service.impl;
import .....;
#Service("jpaUserService")
#Repository
#Transactional
public class UserServiceImpl implements UserService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
#PersistenceContext
private EntityManager em;
#Transactional(readOnly=true)
public User findByUsername(String username) {
........
}
}
my user class
package sg.com.innovax.opscentralv5.table;
import ....;
#Entity
#Table(name = "users", uniqueConstraints = { #UniqueConstraint(columnNames = "username") })
#NamedQueries({
.....
})
public class User implements Serializable {
public static final String ROLE_ADMIN = "ROLE_ADMIN";
public static final String ROLE_USER = "ROLE_USER";
#Id
#SequenceGenerator(name="users_id_seq", sequenceName="users_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="users_id_seq")
#Basic(optional = false)
private Integer id;
#Column(unique=true)
private String username;
private byte[] password;
private String email;
private String mobile;
private Boolean enabled;
private Timestamp deleted;
#OneToOne(cascade=CascadeType.ALL)
#PrimaryKeyJoinColumn
private Role role;
public Integer getId() {
return id;
}
......
}
my user interface
package sg.com.innovax.opscentralv5.table.service;
import ....;
import sg.com.innovax.opscentralv5.table.User;
public interface UserService {
public List<User> findAll();
......;
}
Problems Solved.
2 reasons caused it.
remove <debug/> from security xml
https://jira.springsource.org/browse/SEC-1885
put org.springframework.web.servlet.view.InternalResourceViewResolver class in spring-servlet.xml(previously i put in application context xml).
NOW:
my web.xml
......
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
......
my spring-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
You did not defined UserService aUserService in my root-context.xml.You have to define it like
<beans:bean id="aUserService" class=" UserService implementation classname">
or
add #Service annotation in UserService implementation class.So it will work.
Based on your initial setup the following should work:
Since you specify a name for the bean creation in the #Service("jpaUserService") (http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/stereotype/Service.html) the name of the bean created from annotation scanning is referenced by this name. So you can reference it using that name. For that do the following:
#Autowired
#Qualifier("jpaUserService"")
private UserService aUserService;
Getters and setters are not necessary based on the following https://stackoverflow.com/a/634754/2319179.
Problem:
The autowiring fails because by spring creates proxies using JDK-Dynamic proxies by default (which creates a proxy that implements the interface(s) of the target class). CGLIB-based proxy on the other hand is a subclass of the target class.
See: What is the difference between JDK dynamic proxy and CGLib?
To enable CGLIB based proxying annotate one of your #Configuration classes with
#EnableAspectJAutoProxy(proxyTargetClass=true):
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig
{
...
}
- See more at: http://www.mzan.com/article/35525838-spring-security-config-autowiring-custom-userdetailsservice-bean.shtml#sthash.S3YwrKyC.dpuf
And add :
org.aspectj
aspectjweaver
1.8.9
if necessary

Spring MVC + Hibernate 4 + Spring Security

I have been struggling to make all of this work since days now and don't know what to do. I believe I went through every single post on the subject here on SO and went through douzens of tutorials...
Here is the message I am having at this time:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fruitController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.controller.FruitController.setFruitManager(com.service.FruitManager); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.service.FruitManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I have been able to solve this error in the past, but only to have a new one "No session found for current thread". When not having this one, I got some problem with my Assembler and UserDetailsServiceImpl bean not being recognized in my spring-security.xml file...
I do not think the problem(s) come from my code, I just can't get to set my config files properly and I am probably missing something here.
Here are the config files:
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">
<display-name>Spring MVC Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/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>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<!-- Load everything except #Controllers -->
<context:component-scan base-package="com">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="save*" />
<tx:method name="*" read-only="false" />
</tx:attributes>
</tx:advice>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.dao.HibernateFruitDAO</value>
</list>
</property>
<property name="packagesToScan">
<list>
<value>com.service</value>
<value>com.controller</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</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/basename" />
<property name="username" value="xxx" />
<property name="password" value="yyy" />
</bean>
</beans>
mvc-dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath:hibernate.properties" />
<!-- Load #Controllers only -->
<context:component-scan base-package="com.controller"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
</beans>
spring-security.xml
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/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<beans:bean id="userDetailsService" class="com.service.UserDetailsServiceImpl">
</beans:bean>
<beans:bean id="assembler" class="com.service.Assembler">
</beans:bean>
<http auto-config='true' use-expressions='true'>
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/secure/**" access="hasRole('ROLE_Admin')" />
<logout logout-success-url="/listing.htm" />
<form-login login-page="/login.htm" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login_error.htm" default-target-url="/listing.htm"
always-use-default-target="true" />
</http>
<beans:bean id="com.daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="com.daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
</beans:beans>
FruitController:
package com.controller;
#Controller
public class FruitController{
protected final Log logger = LogFactory.getLog(getClass());
private FruitManager fruitManager;
#Autowired
public void setFruitManager(FruitManager FruitManager) {
this.fruitManager = fruitManager;
}
#RequestMapping(value = "/listing", method = RequestMethod.GET)
public String getFruits(ModelMap model) {
model.addAttribute("fruits", this.fruitManager.getFruits());
return "listing";
}
}
FruitDAO:
public interface FruitDAO {
public List<Fruit> getFruitList();
public List<Fruit> getFruitListByUserId(String userId);
public void saveFruit(Fruitprod);
public void updateFruit(Fruitprod);
public void deleteFruit(int id);
public Fruit getFruitById(int id);
}
HibernateFruitDAO
package com.dao;
#Repository("fruitDao")
public class HibernateFruitDAO implements FruitDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Fruit> getList() {
return (List<Fruit>) getSession().createCriteria ( Fruit.class ).list();
}
public List<Fruit> getFruitListByUserId(String userId) {
return (List<Fruit>)sessionFactory.getCurrentSession().createCriteria("from Fruit where userId =?", userId).list();
}
public void saveFruit(Fruit fruit) {
sessionFactory.getCurrentSession().save(fruit);
}
public void updateFruit(Fruit fruit) {
sessionFactory.getCurrentSession().update(fruit);
}
public void deleteFruit(int id) {
Fruit fruit = (Fruit) sessionFactory.getCurrentSession().load(Fruit.class, id);
if (null != fruit) {
sessionFactory.getCurrentSession().delete(fruit);
}
}
public Fruit getFruitById(int id) {
return (Fruit)sessionFactory.getCurrentSession().load(Fruit.class, id);
}
private Session getSession(){
return sessionFactory.getCurrentSession();
}
}
Interface FruitManager:
package com.service;
import java.io.Serializable;
import java.util.List;
import com.domain.Fruit;
public interface FruitManager extends Serializable{
public List<Fruit> getFruits();
public List<Fruit> getFruitsByUserId(String userId);
public void addFruit(Fruit fruit);
public void removeFruit(int id);
public Fruit getFruitById(int id);
public void updateFruit(Fruit fruit);
}
Implementation of FruitManager:
package com.service;
#Repository("fruitManager")
#Transactional
public class SimpleFruitManager implements FruitManager {
/**
*
*/
private static final long serialVersionUID = ...;
#Autowired
private FruitDAO fruitDao;
public List<Fruit> getFruits() {
return fruitDao.getFruitList();
}
public List<Fruit> getFruitsByUserId(String userId){
return fruitDao.getFruitListByUserId(userId);
}
public void setFruitDao(FruitDAO fruitDao) {
this.fruitDao = fruitDao;
}
public void addFruit(Fruit fruit) {
fruitDao.saveFruit(fruit);
}
public void removeFruit(int id) {
fruitDao.deleteFruit(id);
}
public getFruitById(int id) {
return fruitDao.getFruitById(id);
}
public void updateFruit(Fruit fruit) {
fruitDao.updateFruit(fruit);
}
}
At a glance, it seems you're suffering from a common problem of not understanding how Spring ApplicationContexts fit together to make a web application. See my other answer to exactly the same problem to see if it clears things up:
Declaring Spring Bean in Parent Context vs Child Context
You may also be enlightened by this answer on a similar topic, which links to my previously mentioned answer as well as one other:
Spring XML file configuration hierarchy help/explanation
A couple brief tips to get you headed in the right direction...
By convention, Spring's ContextLoaderListener loads beans from WEB-INF/applicationContext.xml to create the root application context. When you override the default, as you're doing, that file is no longer loaded.
Tip #1: stick with the conventional behavior. It'll make your life simpler.
Also by convention, starting up a Spring DispatcherServlet loads beans from WEB-INF/<servlet name>-context.xml to create the context used to configure the dispatcher servlet. This context becomes a child of the root context.
Tip #2: see tip #1
So you see, you're presently over-configuring things. Read the linked answers and the reference materials linked therein. Learn to work with Spring instead of against it.
In your web.xml file, the applicationContext.xml is never get loaded. You should put it location in context-param. Put the location of mvc-dispatcher-servlet.xml (containing controller related bean) as init-param for DispatcherServlet instead:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
I think you must to use this in the DaoImpl to get the session:
#Autowired
private SessionFactory sessionFactory;

Resources