我可以添加一个优先级来执行方法级别@bean吗?

ff29svar  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(371)

在我的测试应用程序中,我的安全配置类如下所示。

package myProject.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@SuppressWarnings("deprecation")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userService;

    @Override
    public void configure(HttpSecurity theHttp) throws Exception {
        theHttp.authorizeRequests()
                .antMatchers("/design", "/order")
                    .access("hasRole('ROLE_USER')")
                .antMatchers("/", "/**")
                    .access("permitAll")
                .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/", true) 
                .and()
                .logout()
                    .logoutSuccessUrl("/login")
                .and()
                .csrf()
                    .ignoringAntMatchers("/h2-console/**")
                .and()
                .headers()
                    .frameOptions()
                    .sameOrigin();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new StandardPasswordEncoder("53cr3t");
    }

    @Override
    public void configure(AuthenticationManagerBuilder theAuth) throws Exception {
        theAuth.userDetailsService(userService)
                .passwordEncoder(encoder());
    }

}

在那里我定义了encoder(),并将其注解为 @Bean . 这意味着该方法将生成一个由spring容器管理的bean。同样,我需要通过如下所示的构造函数访问编码器。

package myProject.security;

import org.springframework.context.annotation.DependsOn;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import myProject.data.UserRepository;

@Controller
@RequestMapping("/register")
public class RegistrationController {

    private final UserRepository userRepo;
    private final PasswordEncoder passwordEncoder;

    public RegistrationController(UserRepository theUserRepo, PasswordEncoder thePasswordEncoder) {
        this.userRepo = theUserRepo;
        this.passwordEncoder = thePasswordEncoder;
    }

    @GetMapping
    public String registrationForm() {
        return "userRegistry";
    }

    @PostMapping
    public String processRegistration(RegistrationForm theUserRegistration) {
        userRepo.save(theUserRegistration.tranformUser(passwordEncoder));
        return "redirect:/loginPage";
    }

}

用户存储库类

package myProject.data;
import org.springframework.data.repository.CrudRepository;
import myProject.User;

public interface UserRepository extends CrudRepository<User, Long> {

  User findByUsername(String theUsername);

}

用户详细信息服务实现

package myProject.security;

import org.jvnet.hk2.annotations.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import myProject.User;
import myProject.data.UserRepository;

@Service
public class UserRepositoryDetailsService implements UserDetailsService {

    private final UserRepository userRepo;

    @Autowired
    public UserRepositoryUserDetailsService(UserRepository theUserRepository) {
        this.userRepo = theUserRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String theUsername) throws UsernameNotFoundException {
        User user = userRepo.findByUsername(theUsername);
        if (user != null) {
            return user;
        }
        throw new UsernameNotFoundException("User " + theUsername + " not found");
    }

}

在上面的示例中,我使用密码编码器作为构造函数参数。问题是 @Bean 方法的时间构造函数未执行 RegistrationController 被称为。在添加 encoder() 但我不认为这是一个解决方案。有谁能帮我想办法解决我的问题吗。

Error - Error creating bean with name 'registrationController' defined in file [C:\Users\TECH WORLD\IdeaProjects\Project\target\classes\myProject\security\RegistrationController.class]: 
Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 
'securityConfig': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with 
name 'inMemoryUserDetailsManager' defined in class path resource [org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.class]: Bean instantiation 
via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [
org.springframework.security.provisioning.InMemoryUserDetailsManager]: Factory method 'inMemoryUserDetailsManager' threw exception; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'passwordEncoder':

请求的bean当前正在创建中:是否存在无法解析的循环引用?

tyg4sfes

tyg4sfes1#

只需添加 @LazyPasswordEncoder thePasswordEncoder 争论。

afdcj2ne

afdcj2ne2#

事实上,我的问题在将@lazy注解添加到构造函数参数后得到了解决,在进一步操作时,它几乎没有其他问题。我发现了真正的错误。故障出在 UserRepositoryDetailsService 班级。它被注解为 @Service 但在我的代码中,服务是由 import org.jvnet.hk2.annotations.Service; . 但是它应该从 import org.springframework.stereotype.Service; . 一旦我修好了,其他问题都解决了。我花了很长时间才明白我的错误,感谢大家花宝贵的时间帮助我解决问题。

相关问题