| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 |
- 깊이우선탐색
- HTTP
- 백준
- 파이썬 오류
- 자바
- 비지도학습
- 프로그래머스
- 강화학습
- 코딩
- 너비우선탐색
- 오버라이딩
- 딕셔너리
- 멱등
- 지도학습
- 코테
- rest api
- 해시
- 캐싱
- 파이썬
- 이진탐색
- 머신러닝
- Merge sort
- 스택과 힙
- BOJ
- 코딩테스트
- 알고리즘
- 파이썬 알고리즘
- 딥러닝
- bineary search
- post
- Today
- Total
chae._.chae
[Error] BeanCreationException: Error creating bean 본문
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 정보가 부족하다면 추가정보 받아주기(집 주소)
}
}