我很习惯使用 Spring 和 Spring Security,但我不知道为什么这里的依赖注入不起作用。我有一个具有两个基本身份验证系统的应用程序,一个用于用户,一个用于两个管理员。这是 security-context.xml:
<http use-expressions="true">
<intercept-url pattern="/" access="isAuthenticated()" />
<intercept-url pattern="/*" access="isAuthenticated()" />
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')" />
<http-basic />
</http>
<beans:bean id="userDetailsServiceImpl"
class="com.foo.bar.service.LoginServiceImpl" />
<authentication-manager>
<authentication-provider user-service-ref="userDetailsServiceImpl" />
<authentication-provider>
<password-encoder hash="md5" />
<user-service>
<user name="AdminOne" password="eh223rh2efi9hfuwefugwg"
authorities="ROLE_ADMIN" />
<user name="AdminTwo" password="wdkjbcfwerjkbiwfviwefi"
authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
用户认证依赖于 UserDetailsService 的这个实现:
public class LoginServiceImpl implements UserDetailsService {
@Autowired
UserDetailsDAO dao;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
try {
// Get the credentials
return credentials;
} catch (NoResultException exc) {
throw new UsernameNotFoundException("username not found");
} catch (JDBCException jdbce) {
throw new DataAccessException("Cannot acess db", jdbce) {
private static final long serialVersionUID = 1L;
};
}
}
问题是该字段UserDetailsDAO
为空。所以没有注入。奇怪的是,在测试环境中一切正常。并且在服务器启动期间没有抛出异常,这也很奇怪,因为通常会报告自动装配中的错误。顺便说一句,管理员的身份验证就像一个魅力。
如果有用,这是 web.xml: foo
<servlet>
<servlet-name>Foo Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
<!-- Here the context specific for a single project -->
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/datasource-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StreamViewer Dispatcher Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
<!-- Here the context for all the projects -->
/WEB-INF/spring/security-context.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>