울음참고 개발공부
728x90

 

 

 

해당 글에서는 @Autowired로 주입된 빈을 static 메서드에서 사용하려고 할 때 NullPointerException 이 발생하는 원인과 해결방안에 대해 다루려고 한다. 

 

 


문제 상황

 

static 메서드 exctractBrandName() 에서 @Autowired로 주입된 someDAO를 사용하여 실행하면 NullPointerException이 발생한다.

 

 

@Slf4j
@Service("dataService")
public class DataService {

    @Autowired
    private someDAO someDAO;

    public static String extractBrandName(String input) throws Exception {
        List<someVO> brandNameList = someDAO.selectBrandNameKr();
        String[] brandNameKrArr = new String[brandNameList.size()];
        // 추가 로직
        return "result";
    }
}

 

 

문제 원인

  1. @Autowired와 static 필드의 비호환성
    • Spring의 @Autowired는 인스턴스 필드에 의존성을 주입한다. 하지만 static 필드는 클래스 레벨에 속하며, 인스턴스와 관계없이 공유되기 때문에 Spring Context  관리할 수 없게 되기 때문에 결과적으로 static 메서드에서 crawlingDAO를 호출하면 null 값이 반환된다.
  2. Spring의 의존성 주입 시점과 static 필드 초기화 시점
    • static 필드는 클래스 로드 시점에 초기화되지만, Spring의 의존성 주입은 빈이 생성된 이후에 이루어진다. 따라서 static 필드가 초기화될 때는 의존성이 주입되지 않은 상태가 된다.

 

 


 

 

해결 방법

 

1. static 메서드를 인스턴스 메서드로 변경

- static 메서드를 제거하고 인스턴스 메서드로 리팩터링

 

수정 코드

@Slf4j
@Service("dataService")
public class DataService {

    @Autowired
    private SomeDAO someDAO;

    public String extractBrandName(String input) throws Exception {
        List<SignatureCodeVO> brandNameList = someDAO.selectBrandNameKr();
        String[] brandNameKrArr = new String[brandNameList.size()];
        // 추가 로직
        return "result";
    }
}

 

 

 

2. static 필드 초기화 후 사용

- 만약 static 메서드를 꼭 사용해야 한다면, @PostConstruct를 활용해 static 필드를 초기화하여 사용

 

수정 코드

@Slf4j
@Service("dataService")
public class DataService {

    @Autowired
    private SomeDAO someDAO;
    private static SomeDAO statiSomeDAO;

    @PostConstruct
    public void init() {
        statiSomeDAO = someDAO;
    }

    public static String extractBrandName(String input) throws Exception {
        List<SignatureCodeVO> brandNameList = statiSomeDAO.selectBrandNameKr();
        String[] brandNameKrArr = new String[brandNameList.size()];
        // 추가 로직
        return "result";
    }
}

 

 

@PostConstruct를 사용하여 Spring이 SomeDAO를 주입한 후 static 필드를 초기화한다.

이후 static 메서드에서 staticSomeDAO를 사용할 수 있다

 

 


정리

 

@Autowired와 static은 본질적으로 호환되지 않으므로 가능한 한 static 메서드 사용을 피하는 것이 좋다.

 

static 메서드가 꼭 필요한 경우에는 @PostConstruct를 사용하거나 Spring 컨텍스트를 활용하여 의존성을 해결할 수 있다.

 

 


참고 자료

 

+ ) 챗지 

 

 

 

 

728x90
profile

울음참고 개발공부

@메각이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!