Development Tip

web.xml에서 applicationContext.xml 파일 대신 Spring @Configuration 주석이 달린 클래스를 등록하는 방법은 무엇입니까?

yourdevel 2020. 11. 10. 22:20
반응형

web.xml에서 applicationContext.xml 파일 대신 Spring @Configuration 주석이 달린 클래스를 등록하는 방법은 무엇입니까?


웹 응용 프로그램에서 jsf와 spring을 함께 사용하고 있습니다. @Configuration, @ComponentScan등의 주석을 사용하는 하나의 구성 클래스에서 데이터 소스 및 세션 팩토리 를 구성했습니다. 구성 클래스에서 컨텍스트 xml의 모든 항목을 처리하므로 프로젝트에 applicationContext.xml 파일이 없습니다 . 테스트 케이스는 성공적으로 작동하지만 웹 애플리케이션을 배포하면 오류가 발생합니다.

java.lang.IllegalStateException : WebApplicationContext를 찾을 수 없음 : ContextLoaderListener가 등록되지 않았습니까?

이제 web.xml에 리스너 클래스를 제공하면

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

그것은 나에게 오류를 준다.

/WEB-INF/applicationContext.xml을 찾을 수 없습니다.

의 문서에 따라 ContextLoaderListener, 그것은 내가 할 경우하지주고 있다는 사실 contextConfigLocationPARAM에서 web.xml명시 적으로, 그것은라는 기본 스프링 컨텍스트 파일을 검색합니다 applicationContext.xml에서 web.xml. 이제 스프링 컨텍스트 파일을 사용하지 않고 주석으로 모든 구성을 수행하고 싶지 않으면 어떻게해야합니까? ContextLoaderListenerxml 파일을 사용하지 않고 주석 만 사용하여 Spring 및 jsf로 웹 애플리케이션을 실행할 수 있도록 리스너 클래스를 등록하려면 어떻게해야 합니까?


다음으로 web.xml컨텍스트를 부트 스트랩해야합니다 AnnotationConfigWebApplicationContext.

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            org.package.YouConfigurationAnnotatedClass
        </param-value>
    </init-param>
</servlet>

그리고 @EnableWebMvc시작하기 위해 MVC 주석을 사용하는 것을 잊지 마십시오 .

추가 읽기 :

"댓글 후속 조치"=> 튜링 완료로 편집 :

네 물론 청취자가 필요합니다. 위의 내용이 " web.xml에 applicationContext.xml 파일 대신 Spring @Configuration 주석이 달린 클래스를 등록하는 방법 "이라는 질문에 완전히 답했지만 , 여기 전체를 레이아웃하는 Spring 공식 문서 예제 가 있습니다 web.xml.

<web-app>
  <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
       instead of the default XmlWebApplicationContext -->
  <context-param>
      <param-name>contextClass</param-name>
      <param-value>
          org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      </param-value>
  </context-param>

  <!-- Configuration locations must consist of one or more comma- or space-delimited
       fully-qualified @Configuration classes. Fully-qualified packages may also be
       specified for component-scanning -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.acme.AppConfig</param-value>
  </context-param>

  <!-- Bootstrap the root application context as usual using ContextLoaderListener -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Declare a Spring MVC DispatcherServlet as usual -->
  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
           instead of the default XmlWebApplicationContext -->
      <init-param>
          <param-name>contextClass</param-name>
          <param-value>
              org.springframework.web.context.support.AnnotationConfigWebApplicationContext
          </param-value>
      </init-param>
      <!-- Again, config locations must consist of one or more comma- or space-delimited
           and fully-qualified @Configuration classes -->
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>com.acme.web.MvcConfig</param-value>
      </init-param>
  </servlet>

  <!-- map all requests for /app/* to the dispatcher servlet -->
  <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/app/*</url-pattern>
  </servlet-mapping>
</web-app>

여기에 오래된 질문이 있지만 Servlet 3.0 이상을 지원하는 웹 컨테이너에 앱을 배포하는 경우 최신 버전의 Spring (v3.0 +)에서는 이제 web.xml을 모두 제거 할 수 있습니다.

One can implement Spring's WebApplicationInitializer interface to do the same configurations that one would do in web.xml. This implementation class will be automatically detected by Spring 3.0+ app running on Servlet 3.0+ containers.

If the set up is rather simple, you could instead use another class provided by Spring as shown below. All one does here is to set the @Configuration classes and list out the servlet mappings. Keeps the setup extremely simple.

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return new Class[] {AppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
                 "*.html"
                ,"*.json"
                ,"*.do"};
    }
}

참고URL : https://stackoverflow.com/questions/8075790/how-to-register-spring-configuration-annotated-class-instead-of-applicationcont

반응형