gpt4 book ai didi

java - 创建名为 'webSecurityConfig' 的 bean 时出错,因为当我尝试将 UserService Bean Autowiring 到 WebSecurityConfig 中时,它不存在

转载 作者:行者123 更新时间:2023-12-02 10:09:25 25 4
gpt4 key购买 nike

所有 spring mvc + hibernate + spring security 示例都表明我需要创建 MyUserService 类,该类从 springSecurity 扩展 UserDetailsS​​ervice 以将我的数据库与 spring security 绑定(bind)。但当我这样做时,我得到:

Error creating bean with name 'webSecurityConfig' no such bean UserSerivce is defined

因为当我尝试将其自动连接到 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();
}

}

我的用户服务:

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;
}
}

更新:

我有 RunJob 类,它在启动时创建用户,并且 UserService 在其中 Autowiring ,没有错误。这是:

@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/");
}
}

Web应用程序初始化

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[]{"/"};
}
}

最佳答案

如果您的项目有多个配置类,就像我的有 WebMvcConfigWebSecurityConfig 您应该定义注释 @ComponentScan(basePackages = {"com.rjproject"}) 对于每个配置类。

关于java - 创建名为 'webSecurityConfig' 的 bean 时出错,因为当我尝试将 UserService Bean Autowiring 到 WebSecurityConfig 中时,它不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55114827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com