chae._.chae

[Error] BeanCreationException: Error creating bean 본문

Error

[Error] BeanCreationException: Error creating bean

walbe0528 2022. 11. 9. 16:52
728x90
반응형

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: userService cannot be null

 

 

 

Spring Security 공부 중 만난 에러

빈 생성쪽에서 문제가 생긴 것 같았고, 찾아보니 @AllArgsConstructor 어노테이션이 없어 빈 생성이 되지 않아 문제가 발생하였다.

 

1. lombok을 사용하여 해결해주거나

  • @AllArgsConstructor : 모든 필드 값을 파라미터로 받는 생성자를 만드는 어노테이션
  • @RequiredArgsConstructor : final, NotNull인 필드 값만 파라미터로 받는 생성자를 만드는 어노테이션

 

2. 직접 생성자를 만들어 직접 주입하여 해결해준다.

 

 

나는 @AllArgsConstructor 추가해서 해결해주었다. 

 

package com.hcy.security1.config;

import com.hcy.security1.config.oauth.PrincipalOauth2UserService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@AllArgsConstructor
@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터(SecurityConfig)가 스프링 필터체인에 등록된다.
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)  // secured 어노테이션 활성화 , preAuthorize/postAuthorize 어노테이션 활성화
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private PrincipalOauth2UserService principalOauth2UserService;

    @Bean  // 해당 메소드의 리턴되는 오브젝트를 IoC로 등록해준다.
    public BCryptPasswordEncoder encodePwd(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/loginForm")   // 권한이 없는데 요청이 들어오면 로그인 페이지로 이동하도록 설정
//                .usernameParameter("username2")  // 파라미터명 바꾸는 방법
                .loginProcessingUrl("/login")  // /login 주소가 호출되면, 시큐리티가 낚아채서 대신 로그인을 진행해준다!! -> 컨트롤러에 /login 만들 필요X
                .defaultSuccessUrl("/")  // "/loginForm" 요청했을때, 로그인 성공시 메인 페이지로 이동. 다른 특정 페이지를 요청했을 때는 해당 페이지로 이동하게 해줌
                .and()
                .oauth2Login()
                .loginPage("/loginForm")  // 구글 로그인이 완료된 뒤의 후처리가 필요하다. 구글로그인이 완료되면, 코드를 받는게 아니라 (엑세스 토큰 + 사용자 프로필 정보)를 한번에 받는다.
                .userInfoEndpoint()
                .userService(principalOauth2UserService);

        // 1. 코드를 받고(인증)
        // 2. 코드를 통해 액세스 토큰 받고(사용자 정보에 접근할 권한 생긴다)
        // 3. 사용자 프로필 정보 가져온다
        // 4. 해당 정보를 토대로 회원가입을 자동으로 진행시킨다 or 정보가 부족하다면 추가정보 받아주기(집 주소)

    }
}

 

 

728x90