복붙노트

[SPRING] ServletContext를 Autowire 할 수 없습니다.

SPRING

ServletContext를 Autowire 할 수 없습니다.

저는 Spring에 익숙하지 않고 ServletContext에 @Autowire 주석을 클래스 속성과 함께 사용하려고합니다.

@Controller
public class ServicesImpl implements Services{

    @Autowired
    ServletContext context;

dispatcher-servlet.xml에이 클래스에 대한 bean을 정의했습니다.

<bean id="services" class="com.xxx.yyy.ServicesImpl" />

하지만 JUnit 테스트를 실행하려고하면 다음과 같은 오류가 발생합니다.

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

나는 ServletContext injection이 봄에 자동으로 일어난다 고 생각했다. 어떻게 해결할 수 있을까?

감사!

편집 : getRealPath () 메서드를 호출하려면 servletContext 사용하려고합니다. 어떤 대안이 있습니까?

해결법

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

    1.ServletContextAware 인터페이스를 구현하면 Spring에서 직접 삽입한다.

    ServletContextAware 인터페이스를 구현하면 Spring에서 직접 삽입한다.

    @Controller
    public class ServicesImpl implements Services, ServletContextAware{
    
    
    private ServletContext context;
    
    public void setServletContext(ServletContext servletContext) {
         this.context = servletContext;
    }
    
  2. ==============================

    2.단위 테스트에서 사용할 수있는 MockServletContext를 살펴보고 싶을 것이다.

    단위 테스트에서 사용할 수있는 MockServletContext를 살펴보고 싶을 것이다.

  3. ==============================

    3.ServletContext는 Spring 빈이 아니므로 ServletContextAware를 구현하지 않으면 삽입 할 수 없다.

    ServletContext는 Spring 빈이 아니므로 ServletContextAware를 구현하지 않으면 삽입 할 수 없다.

    모듈이나 레이어에서 생각하면 서블릿 컨텍스트가 웹 모듈 / 레이어 외부에서 사용 가능해서는 안됩니다. 귀하의 ServicesImpl이 비즈니스 또는 서비스 계층의 일부라고 생각합니다.

    좀 더 많은 상황을 제시하면 더 나은 대안을 제안 할 수 있습니다.

  4. from https://stackoverflow.com/questions/14895728/cant-autowire-servletcontext by cc-by-sa and MIT license