0

I was going through following post Spring login form example and many other post of Spring Security to create a login example but I was not able to prepare any simple example.

I was trying to incorporate solution from this post Spring login form example but problem is that I want Hibernate session factory to be injected in the UserDAO so that I can write query to get userName from table. @Autowire is not working so I used

<context:annotation-config />
    <context:component-scan
        base-package="com.tcs.ceg" />

but now i am getting runtime exception as cannot autowire sessionFactory as no matching bean found. But a bean with this name I have created in my applicationContext.xml . Can anyone tell me how can I inject sessionFactory? my application-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:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security 
        http://www.springframework.org/schema/security/spring-security-3.1.xsd
        ">
   <context:annotation-config />
    <context:component-scan
        base-package="com.tcs.ceg" />


    <global-method-security pre-post-annotations="enabled" />

    <http pattern="/css/**" security="none"/>
    <http pattern="/images/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/index.jsp" security="none"/>
    <http pattern="/loggedout.jsp" security="none"/>

    <http use-expressions="true">
        <!--
             Allow all other requests. In a real application you should
             adopt a whitelisting approach where access is not allowed by default
          -->
        <intercept-url pattern="/**" access="isAuthenticated()" />
        <form-login />
        <logout logout-success-url="/loggedout.jsp" delete-cookies="JSESSIONID"/>
        <remember-me />

    </http>

    <beans:bean id="myUserService" class="com.tcs.ceg.services.impl.UserServiceImpl" />
    <authentication-manager>
    <authentication-provider user-service-ref="myUserService" />
    </authentication-manager>

</beans:beans>

and my applicationContext.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" >

    <context:annotation-config />
 <mvc:annotation-driven />
    <context:component-scan
        base-package="com.tcs.ceg" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
        <value>
            org.springframework.web.servlet.view.tiles2.TilesView
        </value>
    </property>
    </bean>
    <bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en"/>
</bean>

<bean id="handlerMapping"
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <ref bean="localeChangeInterceptor" />
    </property>
</bean>


<jee:jndi-lookup id="dataSource1" jndi-name="jdbc/PmdDS"/>


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource1" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="current_session_context_class">thread</prop>
                <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>

            </props>
        </property>
    </bean>



    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="1000000000000"/>
    </bean>
</beans>

Code for UserServiceImpl

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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 com.tcs.ceg.dao.intrface.UserDao;
@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private transient UserDao userDao;//userDao is null

    public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user=null;
        try{
            user = userDao.getUser(username);
        }catch(Exception err){
            err.printStackTrace();
        }
        if (user != null) {

            // convert roles

            // initialize user
          return user;
        } else {
            throw new UsernameNotFoundException("No user with username '" + username + "' found!");
        }
    }

}

Code for UserDaoImpl

import java.util.ArrayList;
import java.util.Collection;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Repository;


import com.tcs.ceg.dao.intrface.UserDao;
import com.tcs.ceg.util.lib.DbComparisonException;
@Repository 
public class UserDaoimpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;//sessionfactory is null
    @Override
    public User getUser(String username) throws DbComparisonException {
        String password = "rajesh";
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

          authorities.add(new GrantedAuthorityImpl("admin"));


        User user = new User(username, password, enabled,
          accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        return user;
    }

}

Please note i havent written following line in UserDaoimpl because sessionFactory is null

sessionFactory.getCurrentSession().createQuery("from User").list();//throws null pointer exception
Community
  • 1
  • 1
Rajesh
  • 2,934
  • 8
  • 42
  • 71

1 Answers1

0

I think that the sessionFactory attribute of your DAO must be of type LocalSessionFactoryBean.

EDIT :

In your applicationContext.xml file, you have declared this bean :

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource1" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="current_session_context_class">thread</prop>
                <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>

            </props>
        </property>
    </bean>

which is a org.springframework.orm.hibernate3.LocalSessionFactoryBean.

Then, in your DAO, sessionFactory is a org.hibernate.SessionFactory.

So I think that Spring is unable to autowire your bean in the DAO since it is not the same type.

ndeverge
  • 21,378
  • 4
  • 56
  • 85
  • This is not the issue. A LocalSessionFactoryBean is the correct way to configure a SessionFactory in a Spring application. – Alex Barnes Feb 23 '12 at 10:15
  • 1
    I have solved this by referring this link http://stackoverflow.com/questions/8319115/spring-mvc-spring-security-and-hibernate-cannot-autowire-properties-between-con but I cannot post full answer because my reputation is less than 100 :( ..any ways others who are facing this issue place all ur configuration in a root context and initialise everything as mentioned in this link..things will work – Rajesh Feb 23 '12 at 10:43