IT TIP

Spring MVC : 차이점

itqueen 2020. 11. 20. 17:29
반응형

Spring MVC : 차이점 태그?


며칠 전 저는 Spring Hello World Tutorial : http://viralpatel.net/blogs/spring-3-mvc-create-hello-world-application-spring-3-mvc/ 를 공부하기 시작했습니다.

이 튜토리얼에서 Spring DispatcherServlet은 spring-servlet.xml 파일을 사용하여 구성됩니다 .

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="net.viralpatel.spring3.controller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

이 파일에서 저는 context : component-scan 태그를 사용하여 Spring이 주석을 검색하는 내 파일을 스캔해야한다고 말하고 있습니다. 예를 들어 컨트롤러 클래스가 메서드가 @RequestMapping ( "/ hello") 주석으로 주석 처리되었음을 발견 할 때 이 메서드는 "/ hello"로 끝나는 URL에 대한 HTTP 요청을 처리합니다. 이것은 간단합니다 ...

이제 내 의심은 STS \ Eclipse에서 자동으로 빌드 할 수있는 Spring MVC 템플릿 프로젝트와 관련이 있습니다.

STS에서 새 Spring MVC 프로젝트를 만들 때 DispatcherServlet이전 예제 파일과 유사한 구성을 포함하는 servlet-context.xml 이라는 파일로 구성되어 있습니다.

이 파일에는 여전히 구성 요소 스캔 태그가 있습니다.

<context:component-scan base-package="com.mycompany.maventestwebapp" />

하지만 비슷한 작업이있는 것처럼 보이는 다른 태그도 있습니다.이 태그는 다음과 같습니다.

<annotation-driven />

이 두 태그의 차이점은 무엇입니까?
또 다른 "이상한"점은 이전 예제 (주석 구동 태그를 사용하지 않음)가 Spring MVC 템플릿 프로젝트를 사용하여 STS에서 생성 한 프로젝트와 매우 유사하지만 해당 구성에서 주석 구동 태그를 삭제하면 프로젝트가 실행되지 않고 다음 오류가 발생합니다. HTTP Status 404-

그리고 stacktrace에는 다음이 있습니다.

WARN : org.springframework.web.servlet.PageNotFound-이름이 'appServlet'인 DispatcherServlet에서 URI [/ maventestwebapp /]가있는 HTTP 요청에 대한 매핑을 찾을 수 없습니다.

그런데 왜? 이전 예제는 주석 기반 태그없이 잘 작동하며이 컨트롤러 클래스는 매우 유사합니다. 실제로 "/"경로에 대한 HTTP 요청을 처리하는 방법은 하나뿐입니다.

이것은 내 컨트롤러 클래스의 코드입니다.

package com.mycompany.maventestwebapp;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
*/
@Controller
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

/**
 * Simply selects the home view to render by returning its name.
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate );

    return "home";
}

누군가가 이것을 이해하도록 도울 수 있습니까?

대단히 감사합니다!


<mvc:annotation-driven />이는 실제로 XML에 여러 요소를 지정하거나 인터페이스를 구현하거나 기본 클래스를 확장하지 않고도 스프링 빈 종속성을 정의 할 수 있음을 의미합니다. 예를 들어 @Repository, 클래스가 JpaDaoSupportDaoSupport의 다른 하위 클래스 나 확장 할 필요없이 Dao임을 봄 에 알리기 위해. 마찬가지로 @ControllerSpring은 지정된 클래스에 Controller 인터페이스를 구현하거나 컨트롤러를 구현하는 하위 클래스를 확장하지 않고도 Http 요청을 처리 할 메서드가 포함되어 있음을 알려줍니다.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

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

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.


<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.

<mvc:annotation-driven> 

registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config


Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

참고URL : https://stackoverflow.com/questions/13661985/spring-mvc-difference-between-contextcomponent-scan-and-annotation-driven

반응형