Привет, я пытаюсь реализовать весеннюю безопасность для входа пользователя. Мой файл весна-security.xml являетсяspring security login с CustomUserDetailsService
<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-3.1.xsd">
<http use-expressions="true">
<intercept-url pattern="/home/**" access="isAuthenticated()" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/" access="permitAll" />
<form-login login-page="/cart" authentication-failure-url="/#/login?error=1" always-use-default-target="true"/>
<logout />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService"/>
</authentication-manager>
<beans:bean id="userDetailsService" class="com.dashboard.service.CustomUserDetailsService"/>
</beans:beans>
и вот мой CustomUserDetailsService класс
package com.dashboard.service;
import java.util.Collections;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 static java.util.Arrays.asList;
import com.dashboard.repositories.UserRepository;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Resource
UserService userService;
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
System.out.println("here");
try{
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
com.dashboard.Model.User userObj = userService.getUser(email);
User user = new User(userObj.getUserName(), userObj.getPassword(), true, true, true, true, asList(simpleGrantedAuthority));
return null;
}catch(Exception e){
e.printStackTrace();
return null;
}
//return null;
}
}
и вот мой UserService Класс
package com.dashboard.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dashboard.Model.User;
import com.dashboard.repositories.UserRepository;
@Service
public class UserService {
@Resource
UserRepository userRepository;
public User saveUser(User user){
return userRepository.save(user);
}
public User getUser(String email){
return userRepository.findByEmail(email);
}
}
вот мой файл web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-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>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml,
/WEB-INF/spring/spring-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
My probl эм, когда я отправить форму и отладки приложения, когда я добраться до линии
com.dashboard.Model.User userObj = userService.getUser(email);
мой объект «UserService» имеет нулевое значение, может ли один любезно сказать моему почему боб это нуль. Насколько я понимаю, я объявляю аннотацию @service в начале класса UserService, поэтому не следует ли создавать новый объект bean?
спасибо за ваш ответ, теперь я получаю контекст «префикс» контекст «для элемента»: компонент-сканирование «не связано». Я ищу несколько вопросов, подобных этому в stackoverflow, но не работал для меня. – Shahzeb
@Shahzeb Обратите внимание на то, как вы указываете объявление пространства имен 'xmlns: beans =" http://www.springframework.org/schema/beans "в вашем файле контекста? Вам нужно добавить соответствующий для пространства имен 'context'. Вам также нужно будет обновить 'schemaLocation'. –
Я добавил, и теперь я получаю эту ошибку. Соответствующий шаблон является строгим, но для контекста элемента не найдено объявления: компонент-сканирование. " – Shahzeb