将服务自动连接到控制器代理错误
Autowire Service into controller Proxy error
你好,我是 Spring 的新人。我正在创建一个控制器来连接到一个服务来管理 DAO,但是我收到以下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: es.citic.cms.service.UserService es.citic.cms.controller.UserController.userService; nested exception is java.lang.IllegalArgumentException: Can not set es.citic.cms.service.UserService field es.citic.cms.controller.UserController.userService to com.sun.proxy.$Proxy41
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4772)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
这是我的控制器:
@Controller
public class UserController {
@Autowired
UserService userService;
/** Default GET form handler for users, in submission will call saveRegistration */
@RequestMapping(value = { "/register"}, method = RequestMethod.GET)
public String newRegistration(ModelMap model) {
User user = new User();
// User form will be bind to this User object
model.addAttribute("user", user);
return "enroll";
}
/** This method will be called on form submission, handling POST request,
* It also validates the user input */
@RequestMapping(value = { "/register"}, method = RequestMethod.POST)
public String saveRegistration(@Valid User user, BindingResult result, ModelMap model ){
// add @RequestParam("role") String role
if(result.hasErrors()) {
return "enroll";
}
//userService.createUser(user,new UserRole(user,"hola"));
model.addAttribute("success", "Mr./Mrs. "+ user.getUsername()+" , your registration completed successfully");
return "success";
}
}
这是我使用 DAO 和 Spring 安全方法的服务:
@Service("userService")
public class UserService implements UserDetailsService {
//get user from the database, via Hibernate
@Autowired
private UserDao userDao;
@Transactional(readOnly=true)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUserName(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
return buildUserForAuthentication(user, authorities);
}
@Transactional(readOnly=true)
public boolean createUser(User user, UserRole role) {
return userDao.createUser(user,role);
}
// Converts User to org.springframework.security.core.userdetails.User
private org.springframework.security.core.userdetails.User buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
// Build the user authorities
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
这是我的安全上下文:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/" access="isAuthenticated()" />
<intercept-url pattern="/welcome" access="isAuthenticated()" />
<!--requires-channel="https"-->
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Authentication in a database referenced by the service userService -->
<authentication-manager>
<authentication-provider user-service-ref="userService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="es.citic.cms.service">
</context:component-scan>
<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
我的 servlet 上下文:
<?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"
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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DISPATCHERSERVLET CONTEXT: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<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>
<!-- Scan annotations in the packages -->
<context:component-scan base-package="es.citic.cms.controller" />
<context:component-scan base-package="es.citic.cms.service" />
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename"
value="messages.properties">
</beans:property>
</beans:bean>
还有我的 DAO 实现:
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public User findByUserName(String username) {
User user = null;
user = (User) getSessionFactory().getCurrentSession()
.createQuery("from User where username = :username")
.setParameter("username", username).list().get(0);
return user;
}
@Override
@Transactional
public boolean createUser(User user, UserRole role) {
String hashedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(hashedPassword);
sessionFactory.getCurrentSession().save(user);
sessionFactory.getCurrentSession().save(role);
return true;
}
@Override
public List<User> findAllUsers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<User> findUsersByContaining() {
// TODO Auto-generated method stub
return null;
}
}
我部分遵循了本教程:http://www.mkyong.com/spring-security/spring-security-hibernate-xml-example/
如有任何帮助,我将不胜感激。提前致谢。
您正在尝试自动装配 UserService class,但您应该改为使用该接口,此答案对此进行了更详细的解释:
@Autowired return exception on UserDetails in Spring-security
你好,我是 Spring 的新人。我正在创建一个控制器来连接到一个服务来管理 DAO,但是我收到以下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: es.citic.cms.service.UserService es.citic.cms.controller.UserController.userService; nested exception is java.lang.IllegalArgumentException: Can not set es.citic.cms.service.UserService field es.citic.cms.controller.UserController.userService to com.sun.proxy.$Proxy41
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4772)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
这是我的控制器:
@Controller
public class UserController {
@Autowired
UserService userService;
/** Default GET form handler for users, in submission will call saveRegistration */
@RequestMapping(value = { "/register"}, method = RequestMethod.GET)
public String newRegistration(ModelMap model) {
User user = new User();
// User form will be bind to this User object
model.addAttribute("user", user);
return "enroll";
}
/** This method will be called on form submission, handling POST request,
* It also validates the user input */
@RequestMapping(value = { "/register"}, method = RequestMethod.POST)
public String saveRegistration(@Valid User user, BindingResult result, ModelMap model ){
// add @RequestParam("role") String role
if(result.hasErrors()) {
return "enroll";
}
//userService.createUser(user,new UserRole(user,"hola"));
model.addAttribute("success", "Mr./Mrs. "+ user.getUsername()+" , your registration completed successfully");
return "success";
}
}
这是我使用 DAO 和 Spring 安全方法的服务:
@Service("userService")
public class UserService implements UserDetailsService {
//get user from the database, via Hibernate
@Autowired
private UserDao userDao;
@Transactional(readOnly=true)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUserName(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
return buildUserForAuthentication(user, authorities);
}
@Transactional(readOnly=true)
public boolean createUser(User user, UserRole role) {
return userDao.createUser(user,role);
}
// Converts User to org.springframework.security.core.userdetails.User
private org.springframework.security.core.userdetails.User buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}
// Build the user authorities
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
return Result;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
这是我的安全上下文:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/" access="isAuthenticated()" />
<intercept-url pattern="/welcome" access="isAuthenticated()" />
<!--requires-channel="https"-->
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Authentication in a database referenced by the service userService -->
<authentication-manager>
<authentication-provider user-service-ref="userService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="es.citic.cms.service">
</context:component-scan>
<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
我的 servlet 上下文:
<?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"
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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DISPATCHERSERVLET CONTEXT: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<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>
<!-- Scan annotations in the packages -->
<context:component-scan base-package="es.citic.cms.controller" />
<context:component-scan base-package="es.citic.cms.service" />
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename"
value="messages.properties">
</beans:property>
</beans:bean>
还有我的 DAO 实现:
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public User findByUserName(String username) {
User user = null;
user = (User) getSessionFactory().getCurrentSession()
.createQuery("from User where username = :username")
.setParameter("username", username).list().get(0);
return user;
}
@Override
@Transactional
public boolean createUser(User user, UserRole role) {
String hashedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(hashedPassword);
sessionFactory.getCurrentSession().save(user);
sessionFactory.getCurrentSession().save(role);
return true;
}
@Override
public List<User> findAllUsers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<User> findUsersByContaining() {
// TODO Auto-generated method stub
return null;
}
}
我部分遵循了本教程:http://www.mkyong.com/spring-security/spring-security-hibernate-xml-example/
如有任何帮助,我将不胜感激。提前致谢。
您正在尝试自动装配 UserService class,但您应该改为使用该接口,此答案对此进行了更详细的解释: @Autowired return exception on UserDetails in Spring-security