복붙노트

[SPRING] 순수 자바 기반 설정으로 Spring MVC를 설정하는 방법은?

SPRING

순수 자바 기반 설정으로 Spring MVC를 설정하는 방법은?

나는 아주 단순한 Spring MVC 셋업을 고려할 것이다. 내 applicationContext.xml은 다음과 같습니다.

<mvc:annotation-driven />
<mvc:resources mapping="/css/**" location="/css/" />
<context:property-placeholder location="classpath:controller-test.properties" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/views/" p:suffix=".jsp" />

내 web.xml은 현재 다음과 같습니다.

  <servlet>
   <servlet-name>springDispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map all requests to the DispatcherServlet for handling -->
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

이 설정을 순수 Java 기반 구성으로 변환하려고합니다. 나는 웹을 검색해 왔고, 지금까지 자바 설정을하는 법을 설명하는 내용을 생각해 냈지만 자바 설정을 환경, 즉 웹 컨텍스트에 등록하는 방법을 설명하지 않았다.

지금까지 @Configuration 측면에서 본 것은 다음과 같습니다.

 @Configuration
 @EnableWebMvc
 @PropertySource("classpath:controller.properties")
 @ComponentScan("com.project.web")
 public class WebSpringConfig extends WebMvcConfigurerAdapter {

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/css/**").addResourceLocations("/css/");
 }

 @Bean
 public ViewResolver configureViewResolver() {
     InternalResourceViewResolver viewResolve = new InternalResourceViewResolver();
     viewResolve.setPrefix("/WEB-INF/views/");
     viewResolve.setSuffix(".jsp");

     return viewResolve;
 }

 @Override
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
   configurer.enable();
 }
}

이것을 웹 컨테이너에 어떻게 등록합니까? 나는 최신 스프링 (4.02)을 사용하고있다.

감사!

해결법

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

    1.Java 기반 구성을 지원하려면 web.xml을 다음과 같이 변경해야합니다. DispatcherServlet이 anotation 기반의 자바 설정 AnnotationConfigWebApplicationContext를 사용하여 설정을로드하도록 지시합니다. javaconfig 파일의 위치를 ​​contextConfigLocation 매개 변수로 전달하면됩니다. 아래

    Java 기반 구성을 지원하려면 web.xml을 다음과 같이 변경해야합니다. DispatcherServlet이 anotation 기반의 자바 설정 AnnotationConfigWebApplicationContext를 사용하여 설정을로드하도록 지시합니다. javaconfig 파일의 위치를 ​​contextConfigLocation 매개 변수로 전달하면됩니다. 아래

    <servlet>
      <servlet-name>springDispatcherServlet</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>/*path to your WebSpringConfig*/ </param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    

    업데이트 : web.xml을 변경하지 않고 동일한 작업 수행

    Servlet Specification 3.0은 web.xml을 선택적으로 만들기 때문에 web.xml 없이도이 작업을 수행 할 수 있습니다. 프로그래밍 방식으로 DispatcherServlet을 생성, 구성 및 등록 할 수있게 해주는 ServletContext를 구성하기 위해 WebApplicationInitializer 인터페이스를 구현하거나 구성해야합니다. 좋은 점은 WebApplicationInitializer가 자동으로 감지된다는 것입니다.

    요약은 WebApplicationInitializer를 구현하여 web.xml을 없애기 위해 필요합니다.

     public class MyWebAppInitializer implements WebApplicationInitializer {
    
     @Override
     public void onStartup(ServletContext container) {
      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext =
                           new AnnotationConfigWebApplicationContext();
      rootContext.register(WebSpringConfig.class);
    
      // Manage the lifecycle of the root application context
      container.addListener(new ContextLoaderListener(rootContext));
    
      // Create the dispatcher servlet's Spring application context
      AnnotationConfigWebApplicationContext dispatcherContext =
                         new AnnotationConfigWebApplicationContext();
      dispatcherContext.register(DispatcherConfig.class);
    
      // Register and map the dispatcher servlet
      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
      }
    }
    

    업데이트 : 의견에서 약간 더 복잡한 설명은 공식 스프링 레퍼런스 인 Spring 4 Release에 포함되어있다. 참고:

    http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html

  2. ==============================

    2.web.xml에 요소를 추가하지 않고 Java 기반 구성. WebApplicationInitializer는 Spring의 코드 기반 @Configuration 클래스와 함께 사용하기에 적합합니다.

    web.xml에 요소를 추가하지 않고 Java 기반 구성. WebApplicationInitializer는 Spring의 코드 기반 @Configuration 클래스와 함께 사용하기에 적합합니다.

    WebApplicationInitializer ServletContext를 프로그래밍 방식으로 구성하기 위해 Servlet 3.0 이상의 환경에서 구현되는 인터페이스입니다. 기존의 web.xml 기반 접근 방식과 반대되는 방식 일 수 있습니다. 이 SPI의 구현은 SpringServletContainerInitializer에 의해 자동으로 감지되며,이 자체는 Servlet 3.0 컨테이너에 의해 자동으로 부트 스트랩됩니다. Tomcat 7의 Servlet Spec 3.0 사용하기

    Spring 3.2에서 SrevletContainer에 의해 자동으로 감지되는 WebApplicationInitializer를 구현 한 추상 클래스가 나열되었습니다.

    AbstractAnnotationConfigDispatcherServletInitializer extends
    AbstractDispatcherServletInitializer extends
    AbstractContextLoaderInitializer implements WebApplicationInitializer
    

    Spring 4.1.6.RELEASE 버전을 core, web, webmvc, beans 모듈과 함께 사용합니다.

    public class WebXML_DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { MvcServletXMLConfigurer.class };
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return null;
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[] { "/" };
        }
    
    }
    

    Spring을 이용한 정적 자원 봉사를위한 자바 기반 설정. 봄 부팅

    @Configuration
    @EnableWebMvc // <mvc:annotation-driven />
    @ComponentScan(value = {"com.github.yash777.controllers"})
    // <context:component-scan base-package="com.github.yash777" />
    public class MvcServletXMLConfigurer extends WebMvcConfigurerAdapter implements WebMvcConfigurer {
    
        /**
         * <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
         * p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
         * 
         * @return InternalResourceViewResolver as a bean configuration.
         */
        @Bean
        public InternalResourceViewResolver getInternalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/jsp/");
            resolver.setSuffix(".jsp");
            return resolver;
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
    
            // <mvc:resources mapping="/styles/**" location="/css/" />
            registry
                .addResourceHandler("/styles/**") 
                .addResourceLocations("/css/") // webapp/css/
                .setCachePeriod(3600)
                .resourceChain(true) // Spring 4.1
                .addResolver(new GzipResourceResolver()) // Spring 4.1
                .addResolver(new PathResourceResolver()); // Spring 4.1
    
            // <mvc:resources mapping="/static/**" location="/static/" />
            registry.addResourceHandler("/static/**")
                    .addResourceLocations("/static/", "classpath:/static/") // src/main/resources/static/
                    .setCachePeriod(3600)
                    .resourceChain(true)
                    .addResolver(new PathResourceResolver());
        }
    }
    

    샘플 컨트롤러 나열 :

    @Controller
    @RequestMapping(value = { "/controller", "/c" })
    public class Test extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        @RequestMapping(value = {"/message", "/m"}, method = RequestMethod.GET )
        public void message(HttpServletRequest request, HttpServletResponse response ) throws IOException {
            System.out.println("@Controller Get method called.");
        }
    
        @RequestMapping(value = "/getView", method = RequestMethod.GET )
        public ModelAndView setViewName( Model model ) {
            System.out.println("GET... /getView");
            ModelAndView mav = new ModelAndView();
            mav.setViewName("test");
            return mav;
        }
    }
    

    WEB-INF / web.xml을

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
    </web-app>
    
  3. from https://stackoverflow.com/questions/22315672/how-to-configure-spring-mvc-with-pure-java-based-configuration by cc-by-sa and MIT license