Вызвано: org.springframework.beans.factory.BeanCreationException: ошибка создания bean-компонента с именем securityConfig - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь реализовать тест, но он дает мне эту ошибку, я до сих пор не знаю, почему здесь мой класс securityConfig, это полная ошибка:

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'securityConfig': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean
named 'userService' is expected to be of type
'org.springframework.security.core.userdetails.UserDetailsService' but
was actually of type
'com.devglan.service.UserService$$EnhancerByMockitoWithCGLIB$$837051b7'
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS,"oauth/token").permitAll().and()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/api-docs/**").permitAll();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure( WebSecurity web ) throws Exception {
        web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
    }
}

Вот мой UserServiceImpl

import com.devglan.dao.UserDao;
import com.devglan.model.User;
import com.devglan.service.UserService;
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.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;


@Service(value = "userService")
public class UserServiceImpl implements UserDetailsService, UserService {

    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        User user = userDao.findByUsername(userId);
        if(user == null){
            throw new UsernameNotFoundException("Invalid username or password.");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority(user));
    }

    public Collection<? extends GrantedAuthority> getAuthority(User user) {
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
            list.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));
        return list;
    }

    public List<User> findAll() {
        List<User> list = new ArrayList<>();
        userDao.listUsersByRole().iterator().forEachRemaining(list::add);
        return list;
    }
    @Override
    public User getUserByEmail(String mail) {
        return userDao.findByEmail(mail);
    }

    @Override
    public User getUserByTel(String num) {
        return userDao.findByTel(num);
    }

    @Override
    public void saveAllUsers(List<User> users) {
        userDao.save(users);
    }

    @Override
    public Boolean exist(String email,String matricule) {
        return userDao.existsByEmailAndMatricule(email,matricule);
    }

    @Override
    public Boolean existUser(String username) {
        return userDao.usernamerecord(username);
    }


    @Override
    public void delete(long id) {
        userDao.delete(id);
    }

    @Override
    public User getUser(long id) {return userDao.findOne(id); }
    @Override
    public User getUserByName(String name) { return  userDao.findByUsername(name); }
    @Override
    public User save(User user) {
        return userDao.save(user);
    }

    @Override
    public User editUser(User user) {
        return userDao.saveAndFlush(user);
    }

    @Override
    public User getUserByUserName(String userName) {
        return userDao.findByUsername(userName);
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...