상세 컨텐츠

본문 제목

controller 아닌 class에서 service 호출 하기.

Framework/Spring

by H_Develop 2023. 9. 25. 09:58

본문

this.service is null 계속 이 오류가 떳다.

 ioc컨테이너에 있어야하며 빈 객체로 되어 있어야 service를 호출이 가능하다고 한다.

@Component @Configuration 등 빈 객체로 만들어 주고

service를 @Autowired @Resource를 줘도 안됬다.

 

드디어 방법을 찾았다.

 

https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null

 

Why is my Spring @Autowired field null?

Note: This is intended to be a canonical answer for a common problem. I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I...

stackoverflow.com

나는 applicationContext이 빈에 Spring을 주입하도록 한다:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils {

    public static ApplicationContext ctx;

    /**
     * Make Spring inject the application context
     * and save it on a static variable,
     * so that it can be accessed from any point in the application. 
     */
    @Autowired
    private void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;       
    }
}

원하는 경우 이 코드를 기본 애플리케이션 클래스에도 넣을 수 있습니다.

다른 클래스에서는 다음과 같이 사용할 수 있습니다.

MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);
// Service service = (Service) SpringUtils.ctx.getBean(Service.class);
// get을 만들어 줄 경우, (Service) SpringUtils.get().getBean(Service.class);

이러한 방식으로 애플리케이션의 모든 객체 ( 로 인스턴스화됨 new) 에서 정적 방식으로 모든 Bean을 얻을 수 있습니다 .

 

위 내용과 같이 사용했다.

드디어 됬다.

 

이 방식으로 Service.class의 빈을 얻어 사용하면 된다.

관련글 더보기