[英]Spring Security: Unable to autowired DAO in the UserDetailsService class
This question has been asked many times, and I tired many solutions but failed. 这个问题已经问了很多遍了,我厌倦了许多解决方案,但是失败了。
I'm trying to map the users to the Spring Security users. 我正在尝试将用户映射到Spring Security用户。 My security.xml is able to see my userDao class.
我的security.xml可以看到我的userDao类。 I do not understand why I couldn't autowired my class.
我不明白为什么我不能为课程自动接线。
My spring-security.xml 我的spring-security.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:security="http://www.springframework.org/schema/security"
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/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.memorize" />
<!-- This is where we configure Spring-Security -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/memorize/auth/403" >
<security:intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<security:form-login
login-page="/memorize/auth/login"
authentication-failure-url="/memorize/auth/login?error=true"
default-target-url="/memorize/movie/sp"/>
<security:logout
invalidate-session="true"
logout-success-url="/memorize/login"
logout-url="/memorize/movie/sps"/>
</security:http>
<!-- Declare an authentication-manager to use a custom userDetailsService -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
</beans>
I am scanning all my components by this tag: 我正在通过此标签扫描所有组件:
<context:component-scan base-package="com.memorize" />
This is my springmvc-servlet.xml 这是我的springmvc-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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
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/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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.memorize" />
<mvc:annotation-driven />
<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/springdb" />
<property name="username" value="xxx" />
<property name="password" value="xxx" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>/mappings/Users.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</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 id="usersDAO" class="com.memorize.dao.impl.UsersDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="customUserDetailsService" class="com.memorize.service.CustomUserDetailsService">
<property name="usersDAO" ref="usersDAO" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
And this is my CustomUserDetailsService class 这是我的CustomUserDetailsService类
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UsersDAO usersDAO;
And the error is this: 错误是这样的:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] 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.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
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:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] 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.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] 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:1103)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 38 more
My UsersDao class 我的用户
public interface UsersDAO {
void saveOrUpdate(Users user);
Users find(int userId);
}
My UsersDAOImpl is: 我的用户DAOImpl是:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
@Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
@Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
}
Web.xml Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4">
<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>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/memorize/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
UPDATE 更新
After the suggestions, I changed my UsersDAOImpl as this: 根据建议,我将我的UsersDAOImpl更改为:
My UsersDAOImpl is: 我的用户DAOImpl是:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;
@Repository
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
@Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
@Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
}
However after this change, I get this error: 但是,在进行此更改之后,出现了以下错误:
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.memorize.dao.impl.UsersDAOImpl.sessionFactory;
No qualifying bean of type [org.hibernate.SessionFactory] 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)}.
Now I could not autowired my sessionFactory under UsersDAOImpl class. 现在,我无法自动将sessionFactory连接到UsersDAOImpl类下。
Add a @Repository
annotation to the UsersDAO
implementation so the class can be included in the component scan a添加
@Repository
注解的UsersDAO
实现,因此类可以被包含在组件扫描
@Repository
public class UsersDAOImpl implements UsersDAO {
Its right you are scanning com.memorize 它是您正在扫描的记忆
<context:component-scan base-package="com.memorize" />
But only the classes with annotations like @controller,@service,@component, @Repository etc will be the candidates for auto wiring and the other classes are not.so consider annotating your class accordingly for proper auto wiring. 但是只有带有注解的类(如@ controller,@ service,@ component,@ Repository等)才是自动布线的候选对象,而其他类则不是。
@Component --> generic stereotype for any Spring-managed component @ Component->任何Spring管理的组件的通用构造型
@Repository --> stereotype for persistence layer @Repository- >持久层的构造型
@Service --> stereotype for service layer @Service- >服务层的构造型
@Controller --> stereotype for presentation layer (spring-mvc) @Controller- >表示层的构造型(spring-mvc)
The following should solve the error. 以下应解决该错误。
@Repository
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Users u) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(u);
}
@Override
public void saveOrUpdate(Users user) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
}
@Override
public Users find(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
return (Users) session.get(Users.class, id);
}
} }
I believe that the problem with your config is that UserDao
bean if defined in different context (servlet's one). 我相信您的配置的问题在于,如果
UserDao
bean是在不同的上下文(servlet的上下文)中定义的。 Same goes to SessionFactory
, it won't be autowired. SessionFactory
,它不会自动装配。 My suggestion is to move common beans to root-context, which is loaded in both servlet's and securitie's context. 我的建议是将普通bean移到root-context,它在servlet和securitie的上下文中都加载。
An example: 一个例子:
root-context.xml root-context.xml
In root context I'm autowiring (by component scan) every bean that is not a @Controller
在根上下文中,我将自动装配(通过组件扫描)不是
@Controller
每个bean
<context:component-scan base-package="pl.com.suadeo.nwfm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="regex" expression="pl.com.suadeo.nwfm.webservice.*"/>
</context:component-scan>
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/application.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="${dataSource.name}"/>
<property name="packagesToScan" value="pl.com.suadeo.nwfm.models"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${sessionFactory.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${sessionFactory.hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${sessionFactory.hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${sessionFactory.hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.import_files">${sessionFactory.hibernate.import_files}</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
<!---->
<!--MESSAGE SOURCE-->
<!---->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"/>
<property name="basenames">
<list>
<value>/WEB-INF/message/labels</value>
<value>/WEB-INF/message/form-errors</value>
<value>/WEB-INF/message/messages</value>
</list>
</property>
<property name="useCodeAsDefaultMessage" value="${messageSource.useCodeAsDefaultMessage}"/>
<property name="fallbackToSystemLocale" value="true"/>
<property name="cacheSeconds" value="${messageSource.cacheSeconds}"/>
</bean>
</beans>
servlet-context.xml servlet-context.xml
In servlet context, I'm scanning for @Controller
annotation, enabling spring security and set up some other revelant to servlet config 在Servlet上下文中,我正在扫描
@Controller
批注,以启用Spring安全性并为servlet配置设置一些其他方面
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" 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/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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="pl.com.suadeo.nwfm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/fonts/" mapping="/fonts/**"/>
<mvc:resources location="/favicon.ico" mapping="/favicon.ico"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/static/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/application.properties</value>
</list>
</property>
</bean>
<!---->
<!--MULTIPART RESOLVER-->
<!---->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800"/>
<property name="maxInMemorySize" value="52428800"/>
</bean>
<!---->
<!--SPRING SECURITY-->
<!---->
<security:global-method-security proxy-target-class="true" pre-post-annotations="enabled"/>
</beans>
security-context.xml security-context.xml
In security context, I'm able to see beans from root context, so no need for additional component scan 在安全性上下文中,我能够从根上下文中看到Bean,因此无需其他组件扫描
<?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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/services/**" security="none"/>
<http pattern="/css/**" security="none"/>
<http pattern="/img/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/fonts/**" security="none"/>
<http pattern="/favicon.ico" security="none"/>
<http pattern="/settings/fontSize" security="none"/>
<http auto-config="false" use-expressions="true">
<intercept-url pattern="/login*" access="permitAll()"/>
<intercept-url pattern="/register*" access="permitAll()"/>
<intercept-url pattern="/qualification/tree*/**" access="permitAll()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-processing-url="/processLogin" username-parameter="email" password-parameter="password"
default-target-url="/" always-use-default-target="false" login-page="/login" authentication-failure-url="/login?error=true"/>
<logout logout-url="/logout" logout-success-url="/"/>
</http>
<beans:bean id="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="daoAuthenticationProvider"/>
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsService" class="pl.com.suadeo.nwfm.security.UserDetailsServiceImpl"/>
</beans:beans>
UserServiceImpl.java UserServiceImpl.java
Then in you UserServiceImpl, you may autowire your beans: 然后在UserServiceImpl中,可以自动装配bean:
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
public UserDetails loadUserByUsername( String email ) throws UsernameNotFoundException, DataAccessException {
User userEntity = userRepository.findByEmail( email );
if ( userEntity == null ) {
throw new UsernameNotFoundException( "user not found" );
}
return userService.buildUserFromUserEntity( userEntity );
}
}
Hope this will help 希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.