인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

gabozanet1044's profile image
gabozanet1044

asked

Real-world! Spring Boot and JPA Utilization 2 - API Development and Performance Optimization

Spring @Autowired 필드가 null 인 이유를 모르겠습니다.

Resolved

Written on

·

7.1K

0

public class CustomOAuth2UserService extends DefaultOAuth2UserService {

@Autowired
private MemberRepository memberRepository; // <-- 디버그로 실행하면 이부분이 null 로 확인이 됩니다.

....
    @Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
...
        Member member = memberRepository.findByEmail(email); // <-- 여기서 NullPointException 이 발생합니다.
...
}
 

최초 oauth2 로그인 처리 시 기존 가입자인지 체크하기 위해서 memberRepository 사용하려고 하는데 저 객체가 null 로 되어서 NullPointException 이 발생합니다. 왜 그런걸까요?? ㅠㅠ

아래 컨피그에서 oauth2Login() 부분에서 로그인 처리를 하고 호출하는 방식입니다.

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/oauth2/**", "/login/**", "/signup", "/css/**", "/images/**", "/js/**", "/console/**", "/favicon.ico/**")
.permitAll()
.anyRequest().authenticated()

.and()
.oauth2Login()
.userInfoEndpoint().userService(new CustomOAuth2UserService())

javaspringspring-bootJPA

Answer 1

4

yh님의 프로필 이미지
yh
Instructor

안녕하세요. 조호형님

@Autowired를 사용하려면 CustomOAuth2UserService가 스프링이 관리하는 빈이어야 합니다.

지금 configure(HttpSecurity http) 코드를 보면 new CustomOAuth2UserService() 처럼 직접 생성하고 있습니다. 그러니까 CustomOAuth2UserService는 스프링이 관리하는 빈이 아니라는 뜻이지요. 따라서 @Autowired가 동작하지 않습니다.

스프링 입장에서 내가 관리하는 클래스여야 주입을 할 수 있겠지요?

가장 간단한 방법은 

CustomOAuth2UserService를 @Service, @Component 등으로 스프링 빈으로 등록하신 다음에

configure에서 new 대신에 주입받은 CustomOAuth2UserService를 넣어주시면 됩니다^^

감사합니다.

gabozanet1044's profile image
gabozanet1044

asked

Ask a question