ABOUT ME

-

Today
Yesterday
Total
  • [Springboot/BeanUtils] @Autowired null 문제 해결 (ApplicationContext로 Bean 주입)
    Framework/Spring 2019. 5. 24. 10:22

    새로 생성한 Thread 내에서 DB Mapper의 Service를 호출하여 DB 처리를 하려고 했다.

    하지만 @Autowired로 불러온 Service는 null만 띄울 뿐 동작하지 않았다.

    (Bean으로 등록되는 클래스 내에서만 @Autowired 가 동작)

     

    Spring에서 Bean은 IOC Container가 자동으로 주입해주는데 

    ApplicationContextProvider를 이용하여 Bean을 수동으로 주입 가능하다.

     

    @Component
    public class ApplicationContextProvider implements ApplicationContextAware{
        
        private static ApplicationContext applicationContext;
        
        @Override
        public void setApplicationContext(ApplicationContext ctx) throws BeansException {
            applicationContext = ctx;
        }
        
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
    }

    우선 @Component를 사용하여 ApplicationContextProvider를 생성한다.

     

     

     

     

     

    import org.springframework.context.ApplicationContext;
    
    public class BeanUtils {
        public static Object getBean(String bean) {
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            return applicationContext.getBean(bean);
        }
    }

     그리고 함수를 호출하여 Bean을 가져올 클래스를 하나 생성한다.

    getBean("testService"); 처럼 호출하면 TestService의 Bean을 가져오게 된다.

     

     

    //Service

    @Service
    public class TestService {
    //Service Work
    }

    물론 서비스는 @Service를 이용하여 Bean으로 등록한 상태여야 한다.

     

     

     

    public class TestThread extends Thread {
    	TestSerive testService = (TestSerive) BeanUtils.getBean("testService");

     

     

    위와 같이 이용하면 된다.

    댓글

Copyright 2019. 콩이볼 All rights reserved.