所有spring mvc + hibernate + spring安全示例都说我需要创建MyUserService类,其中从springSecurity扩展了UserDetailsService,以将我的数据库与spring安全性绑定。但是当我这样做时,我得到:错误创建名为“webSecurityConfig”的bean没有定义这样的bean UserSerivce,当我尝试将其自动连接到SecurityConfig时,它尚不存在。当我下载任何在线示例时,给我同样的错误。我在 Git 中的项目 - start_over分支。我的网络安全配置类:@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserService userService;@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder());}@Overrideprotected 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();}@Beanpublic PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder();}}我的用户服务:public interface UserService extends UserDetailsService { void save(User user); List<User> getAllUsers();}我的用户服务简单@Servicepublic 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); }
2 回答
富国沪深
TA贡献1790条经验 获得超9个赞
如果你的项目有多个像我这样的配置类,你应该为每个配置类定义注释。WebMvcConfig
WebSecurityConfig
@ComponentScan(basePackages = {"com.rjproject"})
开心每一天1111
TA贡献1836条经验 获得超13个赞
1 :在你的情况下(javaconfig),你必须定义一个返回对象的Bean,它在哪里定义的?!userService
2 :其他方式,我认为如果你在课堂上添加setter方法,那么问题就会得到解决!就像这样userService
WebSecurityConfig
public void setUserService(UserService userService){ this.userService = userService; }
下一步,在实现从接口的类时,您必须在类的上方添加注释,并将'value'属性设置为“userService”。UserService
@Service
@Service
添加回答
举报
0/150
提交
取消