복붙노트

[SPRING] HandlerInterceptorAdapter에서 서비스를 Autowire 할 수 없습니다. [duplicate]

SPRING

HandlerInterceptorAdapter에서 서비스를 Autowire 할 수 없습니다. [duplicate]

@Autowire를 시도 할 때 NullPointerException이 발생합니다. @Service :

public class PagePopulationInterceptor extends HandlerInterceptorAdapter {
    private @Autowired MyService service;

    public @Override void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) {
        service.savePageView(IPUtils.toLong(request.getRemoteAddr()), request.getRequestURI(), request.getHeader("User-Agent"));
        mav.addObject("counter", service.getCounter());
    }
}

@Configuration
@ComponentScan(basePackages = "com.mycompany", excludeFilters = { @ComponentScan.Filter(Configuration.class) })
@PropertySource("classpath:application.properties")
@EnableTransactionManagement
@EnableWebMvc
public class MyConfig extends WebMvcConfigurerAdapter {
    public @Override void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new PagePopulationInterceptor());
    }
}

@Service
@Transactional
public class MyService {
    private @Autowired PageViewDao pageViewDao;

    public class Counter {
        private long total;
        private long today;
        private long yesterday;
        private long now;

        // Getters and setters
    }

    public void savePageView(long ip, String visitPage, String userAgent) {
        PageView obj = new PageView();
        obj.setVisitDate(new Date());
        obj.setUserAgent(userAgent);
        obj.setPage(visitPage);
        obj.setIp(ip);

        pageViewDao.saveOrUpdate(obj);
    }

    public Counter getCounter() {
        Counter ret = new Counter();
        // populate Counter members
        return ret;
    }
}

편집 : 여기 Stacktrace가 :

java.lang.NullPointerException
    com.mycompany.util.PagePopulationInterceptor.postHandle(PagePopulationInterceptor.java:22)
    org.springframework.web.servlet.HandlerExecutionChain.applyPostHandle(HandlerExecutionChain.java:149)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:934)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

해결법

  1. ==============================

    1.스프링이 PagePopulationInterceptor 인스턴스를 관리하지 않기 때문입니다. 아래 코드에서 직접 만들고 있습니다.

    스프링이 PagePopulationInterceptor 인스턴스를 관리하지 않기 때문입니다. 아래 코드에서 직접 만들고 있습니다.

    public @Override void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new PagePopulationInterceptor());
    }
    

    그걸로 바꿔라.

    @Bean
    public PagePopulationInterceptor pagePopulationInterceptor() {
        return new PagePopulationInterceptor();
    }
    
    public @Override void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(pagePopulationInterceptor());
    }
    

    이런 방식으로, Spring은 PagePopulationInterceptor 인스턴스가 @Bean 메소드에서 생성되기 때문에 수명주기를 관리합니다. Spring은 @Autowired 타겟을 스캔하여 삽입한다.

    여기서는 PagePopulationInterceptor가 @ComponentScaned가되는 패키지에 있다고 가정합니다.

  2. from https://stackoverflow.com/questions/18218386/cannot-autowire-service-in-handlerinterceptoradapter by cc-by-sa and MIT license