创建名称为'webSecurityConfig'的bean时出错,因为当我尝试将其自动装配到WebSecurityConfig中时,UserService Bean不存在

时间:2019-03-12 05:42:32

标签: java spring hibernate spring-mvc spring-security

所有spring mvc + hibernate + spring安全示例都说我需要创建MyUserService类,该类从springSecurity扩展UserDetailsS​​ervice来将我的数据库与spring security绑定在一起。 但是,当我这样做时,我得到:创建名称为“ webSecurityConfig”的bean时出错,未定义此类bean UserSerivce,因为当我尝试将其自动连接到SecurityConfig时,它尚不存在。 当我下载任何在线示例时,都给我同样的错误。

My project in Git-start_over分支。

我的WebSecurityConfig类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired
private UserService userService;


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


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/login", "/").anonymous()
            .antMatchers("/admin", "/admin**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .and()
            .logout().logoutSuccessUrl("/login").permitAll()
            .and()
            .csrf().disable();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

}

我的UserService:

public interface UserService extends UserDetailsService {

    void save(User user);

    List<User> getAllUsers();
}

我的UserServiceImpl

@Service
public class UserServiceImp implements UserService{

    @Autowired
    private UserDao userDao;

    @Transactional
    public void save(User user) {
        userDao.save(user);
    }

    @Transactional(readOnly = true)
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        com.rjproject.entities.User user = userDao.findByUserName(username);
        List<GrantedAuthority> authorities =
                buildUserAuthority(user.getAuthorities());

        return buildUserForAuthentication(user, authorities);

    }

    private org.springframework.security.core.userdetails.User buildUserForAuthentication(com.rjproject.entities.User user,
                                                                                          List<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                user.isEnabled(), true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<Authorities> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (Authorities userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getAuthority()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }
}

UPD:

我有RunJob类,该类在启动时创建用户,并且在那里自动连接UserService且没有错误。在这里:

@Service
public class RunJob implements InitializingBean {

    private static final Logger logger = Logger.getLogger(RunJob.class);
    @Autowired
    private UserService userService;

    public void afterPropertiesSet() {

        User userA = new User();
        userA.setUsername("ARS");
        userA.setPassword("ART");
        Authorities authorityA = new Authorities();
        authorityA.setAuthority("ADMIN");
        authorityA.setUser(userA);
        Set<Authorities> roles = new HashSet<>();
        roles.add(authorityA);
        userA.setAuthorities(roles);
        userService.save(userA);
        logger.info("user " + userA.getUsername() + " " + userA.getPassword() + " is saved with " + authorityA.getAuthority() + " authority");

        User userB = new User();
        userB.setUsername("John");
        userB.setPassword("Doe");
        Authorities authorityB = new Authorities();
        authorityB.setAuthority("USER");
        authorityB.setUser(userB);
        roles.clear();
        roles.add(authorityB);
        userB.setAuthorities(roles);
        userService.save(userB);
        logger.info("user " + userB.getUsername() + " " + userB.getPassword() + " is saved with " + authorityB.getAuthority() + " authority");
    }
}

下载任何在线示例时,我都会得到完全相同的错误。 SpringSecurity本身。 UPD2: 这是所有配置类。

webMvcConfig

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.rjproject"})
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(true);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

WebAppInit

public class WebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { HibernateConfig.class, WebSecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

1 个答案:

答案 0 :(得分:0)

1:在您的情况下(javaconfig),您必须定义一个返回userService对象的Bean,它在哪里定义?!

2:换句话说,我想如果您在userService类中为WebSecurityConfig添加了setter方法,那么问题就解决了!就是这样

public void setUserService(UserService userService){
     this.userService = userService;
}

下一步,在UserService接口中实现类,您必须在类上方添加@Service批注,并将@Service的'value'属性设置为“ userService”。