2013-08-05 100 views
0

我一直在为Spring MVC + Spring Security + hibernate做一个登录页面的例子,但现在我遇到了一个问题,燃料@Autowire一直给我空值。服务器不报告任何错误,只是它没有完成操作。Autowired Field is Null

CustomUSerDetailsS​​ervice.java

package com.carloscortina.paidosSimple.service; 

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

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
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 org.springframework.security.core.GrantedAuthority; 
import org.springframework.security.core.authority.SimpleGrantedAuthority; 

import com.carloscortina.paidosSimple.dao.UsuarioDao; 
import com.carloscortina.paidosSimple.model.Usuario; 

@Service 
@Transactional(readOnly=true) 
public class CustomUserDetailsService implements UserDetailsService { 

    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class); 

    @Autowired UsuarioDao userDao; 

    @Override 
    public UserDetails loadUserByUsername(String username) 
      throws UsernameNotFoundException { 

     logger.info(username); 
     Usuario domainUser = userDao.getUsuario(username); 
     logger.info(domainUser.getUsername()); 

     boolean enabled = true; 
     boolean accountNonExpired = true; 
     boolean credentialsNonExpired = true; 
     boolean accountNonLocked = true; 

     return new User(
      domainUser.getUsername(), 
      domainUser.getPassword(), 
      enabled, 
      accountNonExpired, 
      credentialsNonExpired, 
      accountNonLocked, 
      getAuthorities(domainUser.getRol().getId())); 
    } 

    public Collection<? extends GrantedAuthority> getAuthorities(Integer rol){ 
     List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(rol)); 
     return authList; 
    } 

    public List<String> getRoles(Integer rol){ 
     List<String> roles = new ArrayList<String>(); 

     if(rol.intValue() == 1){ 
      roles.add("ROLE_DOCTOR"); 
      roles.add("ROLE_ASISTENTE"); 
     }else if (rol.intValue() == 2){ 
      roles.add("ROLE_ASISTENTE"); 
     } 
     return roles; 
    } 

    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; 

    } 

} 

这里领域userDao保持beign空,因此当我尝试使用userDao.getUsuario(username)操作只是不继续,它不报告错误或类似它只是给了我一个404-错误

UsuarioDao.xml

package com.carloscortina.paidosSimple.dao; 

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


import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

import com.carloscortina.paidosSimple.model.Usuario; 

@Repository 
public class UsuarioDaoImp implements UsuarioDao { 

    private static final Logger logger = LoggerFactory.getLogger(UsuarioDaoImp.class); 

    @Autowired 
    private SessionFactory sessionFactory; 

    private Session getCurrentSession(){ 
     return sessionFactory.getCurrentSession(); 
    } 

    @Override 
    public Usuario getUsuario(String username) { 
     logger.debug("probando"); 
     List<Usuario> userList = new ArrayList<Usuario>(); 
     Query query = getCurrentSession().createQuery("from Usuario u where u.Username = :username"); 
     query.setParameter("username", username); 
     userList = query.list(); 
     if (userList.size() > 0){ 
      return (Usuario) userList.get(0); 
     }else{ 
      return null; 
     } 
    } 

} 

的servlet-context.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:tx="http://www.springframework.org/schema/tx" 
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 

    <!-- Enable transaction Manager --> 
    <tx:annotation-driven/> 

    <!-- DataSource JNDI --> 
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" /> 

    <!-- Session factory --> 
    <beans:bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
     p:dataSource-ref="dataSource" 
     p:hibernateProperties-ref="hibernateProperties" 
     p:packagesToScan="com.carloscortina.paidosSimple.model" /> 

    <!-- Hibernate Properties --> 
    <util:properties id="hibernateProperties"> 
     <beans:prop key="hibernate.dialect"> 
      org.hibernate.dialect.MySQL5InnoDBDialect 
     </beans:prop> 
     <beans:prop key="hibernate.show_sql">false</beans:prop> 
    </util:properties> 

    <beans:bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager" 
     p:sessionFactory-ref="sessionFactory" /> 

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 

    <context:component-scan base-package="com.carloscortina.paidosSimple" /> 

</beans:beans> 

我不知道什么是缺失,所以任何想法的欢迎,在此先感谢。

编辑: UsuarioDaoImp

package com.carloscortina.paidosSimple.dao; 

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


import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

import com.carloscortina.paidosSimple.model.Usuario; 

@Repository 
public class UsuarioDaoImp implements UsuarioDao { 

    private static final Logger logger = LoggerFactory.getLogger(UsuarioDaoImp.class); 

    @Autowired 
    private SessionFactory sessionFactory; 

    private Session getCurrentSession(){ 
     return sessionFactory.getCurrentSession(); 
    } 

    @Override 
    public Usuario getUsuario(String username) { 
     logger.debug("probando"); 
     List<Usuario> userList = new ArrayList<Usuario>(); 
     Query query = getCurrentSession().createQuery("from Usuario u where u.Username = :username"); 
     query.setParameter("username", username); 
     userList = query.list(); 
     if (userList.size() > 0){ 
      return (Usuario) userList.get(0); 
     }else{ 
      return null; 
     } 
    } 

} 

试图与UsuarioDaoImp添加一个bean我得到这个错误后:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioServicioImp': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.carloscortina.paidosSimple.dao.UsuarioDao com.carloscortina.paidosSimple.service.UsuarioServicioImp.usuarioDao; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.carloscortina.paidosSimple.dao.UsuarioDao] is defined: expected single matching bean but found 2: usuarioDaoImp,userDao 

UsuarioServiceImp

package com.carloscortina.paidosSimple.service; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

import com.carloscortina.paidosSimple.dao.UsuarioDao; 
import com.carloscortina.paidosSimple.model.Usuario; 

@Service 
@Transactional 
public class UsuarioServicioImp implements UsuarioService{ 

    @Autowired 
    private UsuarioDao usuarioDao; 

    @Override 
    public Usuario getUsuario(String username) { 
     return usuarioDao.getUsuario(username); 
    } 

} 

我想我在短关于这个问题的知识,那为什么我要跟着一个例子,但我结束了因此,如果我没有正确地给出信息或者我误解了概念,我很抱歉。

弹簧security.xml文件

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns:security="http://www.springframework.org/schema/security" 
    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:tx="http://www.springframework.org/schema/tx" 
    xmlns:jee="http://www.springframework.org/schema/jee" 
    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.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd 
     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> 


    <beans:bean class="com.carloscortina.paidosSimple.service.CustomUserDetailsService" id="customUserDetailsService"></beans:bean> 

    <security:http auto-config="true"> 
     <security:intercept-url pattern="/sec/moderation.html" access="ROLE_ASISTENTE" /> 
     <security:intercept-url pattern="/admin/*" access="ROLE_DOCTOR" /> 
     <security:form-login login-page="/user-login.html" 
      default-target-url="/success-login.html" 
      authentication-failure-url="/error-login.html" /> 
     <security:logout logout-success-url="/index.html" /> 
    </security:http> 

    <security:authentication-manager> 
     <security:authentication-provider user-service-ref="customUserDetailsService"> 
      <security:password-encoder hash="plaintext" /> 
     </security:authentication-provider> 
    </security:authentication-manager> 

</beans:beans> 
+0

你在哪里创建UsuarioDaoImp豆? –

+0

好吧,它是由弹簧使用注释@@ UsuarioDaoImp – Ccortina

回答

3

您是如何访问CustomUSerDetailsS​​ervice类?我希望你没有在安全配置文件或其他任何spring配置文件中添加这个类作为bean?

Editted: 您的服务bean被注解为@服务,你也宣布它在XML中,春天已经创建了两个服务组件一个基于@Service注释(完全组装为autowried)和第二使用XML配置(我假设你没有注入dao依赖关系),所以第二个没有设置dao对象。由于您正在使用安全配置中声明的服务bean的bean名称,因此在调试时将userDao设置为null。

要么在安全xml中注释显式bean定义,直接使用ref =“customUSerDetailsS​​ervice”作为@service注释已在spring上下文中添加具有此名称的bean。

即注释/删除这条线在你的安全配置和每件事情应该工作。

<beans:bean class="com.carloscortina.paidosSimple.service.CustomUserDetailsService" id="customUserDetailsService"></beans:bean> 

当你注解为@组件/ @服务春豆增添与名称的豆等于短类名(首字母小写),所以豆名称为“customUserDetailsS​​ervice”已经存在,在明确界定它xml重写它。

或宣布所有的bean定义(包括有依赖性)明确它的XML配置

+0

wel ..是的,我在安全xml中添加了一个bean。 – Ccortina

+0

所以现在有两个服务bean,一个自动装配正确,但没有被使用,另一个在xml中没有被userDao填充。尝试在ref中使用服务bean名称而不声明xml中的服务bean – coder

+0

im很抱歉,但我该怎么做?我仍然习惯春天的术语和概念。 – Ccortina

1

的DAO组件添加到组件扫描

<context:component-scan base-package="com.carloscortina.paidosSimple, com.carloscortina.paidosSimple.dao" /> 
+0

上的@@ Repository的线,谢谢,但它没有工作.. userDao的价值保持良好的空 – Ccortina

+0

它是否抛出任何异常..你能显示错误吗? –

+0

那也是我的问题,它显示没有错误或例外。我只知道它的null,因为我使用了Spring Tool Suite的调试并添加了一个breakline,并且它表示该值为null。 – Ccortina