如何摆脱这个异常“没有定义名为'userDetailsService'的bean”虽然它是在xml文件中定义的?
Posted
技术标签:
【中文标题】如何摆脱这个异常“没有定义名为\'userDetailsService\'的bean”虽然它是在xml文件中定义的?【英文标题】:How to get rid of this exception " No bean named 'userDetailsService' is defined" although it is defined in xml file?如何摆脱这个异常“没有定义名为'userDetailsService'的bean”虽然它是在xml文件中定义的? 【发布时间】:2017-02-04 01:44:03 【问题描述】:我正在尝试使用面向数据库的问题进行 Spring 安全身份验证
DataController.java
package com.anzy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.anzy.dao.DataDao;
import com.anzy.domain.Employee;
@Controller
public class DataController
@Autowired
DataDao dataDao;
@RequestMapping("form")
public ModelAndView getForm(@ModelAttribute Employee employee)
return new ModelAndView("form");
@RequestMapping("register")
public ModelAndView registerUser(@ModelAttribute Employee employee)
dataDao.insertRow(employee);
return new ModelAndView("redirect:list");
@RequestMapping("list")
public ModelAndView getList()
List employeeList = dataDao.getList();
return new ModelAndView("list", "employeeList", employeeList);
@RequestMapping("delete")
public ModelAndView deleteUser(@RequestParam int id)
dataDao.deleteRow(id);
return new ModelAndView("redirect:list");
@RequestMapping("edit")
public ModelAndView editUser(@RequestParam int id,
@ModelAttribute Employee employee)
Employee employeeObject = dataDao.getRowById(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
@RequestMapping("update")
public ModelAndView updateUser(@ModelAttribute Employee employee)
dataDao.updateRow(employee);
return new ModelAndView("redirect:list");
用户.java
package com.anzy.domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
public class User implements Serializable
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@ManyToMany
@JoinTable(name="UserAndRoles",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(name="role_id"))
private List<Role> roles;
@Enumerated(EnumType.STRING)
private UserStatus status;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public UserStatus getStatus()
return status;
public void setStatus(UserStatus status)
this.status = status;
public List<Role> getRoles()
return roles;
public void setRoles(List<Role> roles)
this.roles = roles;
角色.java
package com.anzy.domain;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
public class Role
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="roleName")
private String roleName;
@ManyToMany(mappedBy="roles")
private List<User>users;
public Role(int id, String roleName, List<User> users)
super();
this.id = id;
this.roleName = roleName;
this.users = users;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getRoleName()
return roleName;
public void setRoleName(String roleName)
this.roleName = roleName;
public List<User> getUsers()
return users;
public void setUsers(List<User> users)
this.users = users;
用户状态.java
package com.anzy.domain;
public enum UserStatus
ACTIVE,
INACTIVE;
Employee.java
package com.anzy.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="employetest")
public class Employee
@Id
@GeneratedValue
private int id;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "phone")
private String phone;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getFirstName()
return firstName;
public void setFirstName(String firstName)
this.firstName = firstName;
public String getLastName()
return lastName;
public void setLastName(String lastName)
this.lastName = lastName;
public String getEmail()
return email;
public void setEmail(String email)
this.email = email;
public String getPhone()
return phone;
public void setPhone(String phone)
this.phone = phone;
UserDao.java
package com.anzy.dao;
import java.util.List;
import com.anzy.domain.User;
public interface UserDao
void addUser(User user);
void editUser(User user);
void deleteUser(int userId);
User findUser(int useId);
User findUserByName(String username);
List<User> getAllUser();
UserDaoImpl.java
package com.anzy.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.anzy.domain.User;
@Repository
public class UserDaoImpl implements UserDao
@Autowired
private SessionFactory session;
public void addUser(User user)
session.getCurrentSession().save(user);
public void editUser(User user)
session.getCurrentSession().update(user);
public void deleteUser(int userId)
session.getCurrentSession().delete(findUser(userId));
public User findUser(int userId)
return (User) session.getCurrentSession().get(User.class,userId);
public User findUserByName(String username)
Criteria criteria=session.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq("username", username));
return (User)criteria.uniqueResult();
public List<User> getAllUser()
// TODO Auto-generated method stub
return session.getCurrentSession().createQuery("from User").list();
UserDetailsServiceImpl.java
package com.anzy.services;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.transaction.annotation.Transactional;
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.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.anzy.dao.UserDao;
import com.anzy.domain.Role;
import com.anzy.domain.User;
import com.anzy.domain.UserStatus;
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService
@Autowired
private UserDao userDao;
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
User user=userDao.findUserByName(username);
if(user!=null)
String password=user.getPassword();
boolean enabled=user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
boolean credentialsNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonLocked=user.getStatus().equals(UserStatus.ACTIVE);
Collection <GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
for(Role role:user.getRoles())
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
org.springframework.security.core.userdetails.User secureUser=new org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return secureUser;
else
throw new UsernameNotFoundException("User not found !!!");
DataDao.java
package com.anzy.dao;
import java.util.List;
import com.anzy.domain.Employee;
public interface DataDao
public int insertRow(Employee employee);
public List<Employee> getList();
public Employee getRowById(int id);
public int updateRow(Employee employee);
public int deleteRow(int id);
DataDaoImpl.java
package com.anzy.dao;
import java.io.Serializable;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.anzy.domain.Employee;
public class DataDaoImpl implements DataDao
@Autowired
SessionFactory sessionFactory;
@Transactional
public int insertRow(Employee employee)
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
public List getList()
Session session = sessionFactory.openSession();
@SuppressWarnings("unchecked")
List employeeList = session.createQuery("from Employee")
.list();
session.close();
return employeeList;
public Employee getRowById(int id)
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.load(Employee.class, id);
System.out.println(employee);
return employee;
public int updateRow(Employee employee)
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
public int deleteRow(int id)
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee employee = (Employee) session.load(Employee.class, id);
session.delete(employee);
tx.commit();
Serializable ids = session.getIdentifier(employee);
session.close();
return (Integer) ids;
spring-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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.anzy" />
<context:property-placeholder location="classpath:database.properties" />
<mvc:annotation-driven />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="$database.driver" />
<property name="url" value="$database.url" />
<property name="username" value="$database.user" />
<property name="password" value="$database.password" />
<property name="initialSize" value="20" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.anzy.domain.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">$hibernate.dialect</prop>
<prop key="hibernate.show_sql">$hibernate.show_sql</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
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="dataDaoImpl" class="com.anzy.dao.DataDaoImpl" />
<!-- <bean id="dataServiceImpl" class="com.beingjavaguys.services.DataServiceImpl" />
-->
</beans>
spring-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/*" access="isAuthenticated()"/>
<form-login />
<!-- <logout invalidate-session="true" />
--> </http>
<!-- <authentication-manager>
<authentication-provider>
<user-service>
<user name="joseph" password="bagnes" authorities="Admin,User" />
<user name="bernabe" password="jose" authorities="User" />
</user-service>
</authentication-provider>
</authentication-manager> -->
<beans:bean id="daoAuthenticationProvider" class=" org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"></beans:property>
</beans:bean>
<beans:bean id="authenticationManager" class="org.springframework.security.authentication.AuthenticationProvider">
<beans:property name="providers">
<beans:list>
<beans:ref local="daoAuthenticationProvider"/>
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5"></password-encoder>
</authentication-provider>
</authentication-manager>
</beans:beans>
web.xml
<web-app 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"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
</web-app>
【问题讨论】:
我编辑了答案,它现在应该可以工作了(对于您的项目的简化版本)。一般来说,也许很明显,尽可能地简化这些问题通常会使他们的解决方案更容易。我还认为你的问题被否决了,因为你没有充分简化你的项目,同时保留了错误,并以最简单的设置提出问题。 @JohnDonn,最好是教如何钓鱼或在哪里钓到鱼,而不是直接喂鱼。 @John Dohn,谢谢大家。 @JohnDonn 感谢朋友的帮助,我尝试过这种方式现在效果很好,在此之前我选择了替代解决方案,即。纯 Spring Java 配置也适用于我 :) . @SundararajGovindasamy 我很欣赏你的话。它只是我是 Spring 框架的新手,并尝试更多地使用它。 【参考方案1】:(从以前的版本编辑)
我为您的问题创建了一个简化设置,并让代码正常工作。
这里有两个Java类,首先是服务(本质上是一个stub,我没有尝试进一步简化,代码没有特别意义):
package com.anzy.services;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
Collection <GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
org.springframework.security.core.userdetails.User secureUser=new org.springframework.security.core.userdetails.User("user", "user", true, true, true, true, authorities);
return secureUser;
这里是控制器(再次简化为只有一种方法)
package com.anzy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DataController
@RequestMapping("form")
public ModelAndView getForm()
return new ModelAndView("form");
WEB-INF下的四个文件分别是:
spring-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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.anzy">
<context:exclude-filter type="regex" expression="com.anzy.controller.*"/>
</context:component-scan>
<mvc:annotation-driven />
<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>
</beans>
spring-mvc.xml
<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"
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">
<context:component-scan base-package="com.anzy.controller"/>
</beans>
spring-security.xml(注意我在元素<http..
中添加了use-expressions="true"
)
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns:bean="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="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/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/*" access="isAuthenticated()"/>
<form-login />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService"/>
</authentication-manager>
</bean:beans>
web.xml
<web-app 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"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
/WEB-INF/spring-config.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
</web-app>
生成的 Web 应用程序毫无例外地启动。
但是,如果我在 web.xml 中进行更改
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
/WEB-INF/spring-config.xml
</param-value>
</context-param>
到
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
和
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
到
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
那么我得到的正是你问题主题的例外
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userDetailsService' is defined
【讨论】:
我试了你的朋友,得到了更复杂的错误,包括以前的错误:)以上是关于如何摆脱这个异常“没有定义名为'userDetailsService'的bean”虽然它是在xml文件中定义的?的主要内容,如果未能解决你的问题,请参考以下文章