SpringMVCはJava類で構成されています。
26993 ワード
もっと読む
SpringMVCはJava類で構成されています。
SpringMVCを使用する場合はXMLの配置を望まず、Java類による配置を採用しても良いです。また、Dispactch Servletをweb.xmlに配置したい場合は、init-paramでcontext ClassをAnnotationConfigWebApplication Controtextと指定し、context CofigLocationをSpring MVC配置Java類のフルパス名に指定する必要があります。
その後、いくつかのSprigMVC構成beanをこの構成クラスで定義することができ、例えば、次のようにInternal Resource View Resoliverを定義します。
配置時にはWebMvcConfigrerインターフェースを選択して配置したり、抽象的なWebMvcConfigrer Adapterから継承して興味のある方法を書き直したりすることもできます。以下はWebMvcConfigrerの定義です。
Java構成を使用する場合も、構成クラスで
DisplatServletをweb.xmlファイルで定義しないでほしいなら、完全にプログラムで定義して、AbstractDisplatDisplatServletInitializerを定義するサブクラスを選択して、抽象的な方法を実現します。注解に基づく構成が必要であれば、直接にAbstractAnnotationConfigDisparer ServletInitializerクラスを継承することができる。AbstractAnnotationConfigDisplatServletInitializerでは、3つの抽象的な方法が定義されています。
SpringMVCはJava類で構成されています。
SpringMVCを使用する場合はXMLの配置を望まず、Java類による配置を採用しても良いです。また、Dispactch Servletをweb.xmlに配置したい場合は、init-paramでcontext ClassをAnnotationConfigWebApplication Controtextと指定し、context CofigLocationをSpring MVC配置Java類のフルパス名に指定する必要があります。
<servlet>
<servlet-name>springservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextClassparam-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContextparam-value>
init-param>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>com.elim.spring.mvc.MvcConfigurationparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
Java構成クラスでは、通常のJavaクラス構成のように定義され、次のようにスキャンcom.elim.spring.mvc.controller
パケットの下のクラスを定義します。@ComponentScan(basePackages = "com.elim.spring.mvc.controller")
public class MvcConfiguration {
}
Displatch Servletを定義する場合、または指定されたプロファイルがXMLファイルであれば、上記のJavaプロファイルを対応するXMLプロファイルに定義することもできます。効果は同じです。その後、いくつかのSprigMVC構成beanをこの構成クラスで定義することができ、例えば、次のようにInternal Resource View Resoliverを定義します。
@ComponentScan(basePackages = "com.elim.spring.mvc.controller")
public class MvcConfiguration {
@Bean
public InternalResourceViewResolver newInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
}
WebMvcConfigrer配置時にはWebMvcConfigrerインターフェースを選択して配置したり、抽象的なWebMvcConfigrer Adapterから継承して興味のある方法を書き直したりすることもできます。以下はWebMvcConfigrerの定義です。
public interface WebMvcConfigurer {
/**
* Add {@link Converter}s and {@link Formatter}s in addition to the ones
* registered by default.
*/
void addFormatters(FormatterRegistry registry);
/**
* Configure the {@link HttpMessageConverter}s to use in argument resolvers
* and return value handlers that support reading and/or writing to the
* body of the request and response. If no message converters are added to
* the list, default converters are added instead.
* @param converters initially an empty list of converters
*/
void configureMessageConverters(List<HttpMessageConverter>> converters);
/**
* Provide a custom {@link Validator} instead of the one created by default.
* The default implementation, assuming JSR-303 is on the classpath, is:
* {@link org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean}.
* Leave the return value as {@code null} to keep the default.
*/
Validator getValidator();
/**
* Configure content negotiation options.
*/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/**
* Configure asynchronous request handling options.
*/
void configureAsyncSupport(AsyncSupportConfigurer configurer);
/**
* Helps with configuring HandlerMappings path matching options such as trailing slash match,
* suffix registration, path matcher and path helper.
* Configured path matcher and path helper instances are shared for:
* <ul>
* <li>RequestMappings
* <li>ViewControllerMappings
* <li>ResourcesMappings
*
* @since 4.0.3
*/
void configurePathMatch(PathMatchConfigurer configurer);
/**
* Add resolvers to support custom controller method argument types.
* <p>This does not override the built-in support for resolving handler
* method arguments. To customize the built-in support for argument
* resolution, configure {@link RequestMappingHandlerAdapter} directly.
* @param argumentResolvers initially an empty list
*/
void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers);
/**
* Add handlers to support custom controller method return value types.
* <p>Using this option does not override the built-in support for handling
* return values. To customize the built-in support for handling return
* values, configure RequestMappingHandlerAdapter directly.
* @param returnValueHandlers initially an empty list
*/
void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers);
/**
* Configure the {@link HandlerExceptionResolver}s to handle unresolved
* controller exceptions. If no resolvers are added to the list, default
* exception resolvers are added instead.
* @param exceptionResolvers initially an empty list
*/
void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers);
/**
* Add Spring MVC lifecycle interceptors for pre- and post-processing of
* controller method invocations. Interceptors can be registered to apply
* to all requests or be limited to a subset of URL patterns.
*/
void addInterceptors(InterceptorRegistry registry);
/**
* Provide a custom {@link MessageCodesResolver} for building message codes
* from data binding and validation error codes. Leave the return value as
* {@code null} to keep the default.
*/
MessageCodesResolver getMessageCodesResolver();
/**
* Configure simple automated controllers pre-configured with the response
* status code and/or a view to render the response body. This is useful in
* cases where there is no need for custom controller logic -- e.g. render a
* home page, perform simple site URL redirects, return a 404 status with
* HTML content, a 204 with no content, and more.
*/
void addViewControllers(ViewControllerRegistry registry);
/**
* Configure view resolvers to translate String-based view names returned from
* controllers into concrete {@link org.springframework.web.servlet.View}
* implementations to perform rendering with.
*/
void configureViewResolvers(ViewResolverRegistry registry);
/**
* Add handlers to serve static resources such as images, js, and, css
* files from specific locations under web application root, the classpath,
* and others.
*/
void addResourceHandlers(ResourceHandlerRegistry registry);
/**
* Configure a handler to delegate unhandled requests by forwarding to the
* Servlet container's "default" servlet. A common use case for this is when
* the {@link DispatcherServlet} is mapped to "/" thus overriding the
* Servlet container's default handling of static resources.
*/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
}
WebMvcConfigrer Adapterを継承する方式で、上の構成は次のように書き換えられます。@ComponentScan(basePackages = "com.elim.spring.mvc.controller")
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
}
@EnbleWebMvcJava構成を使用する場合も、構成クラスで
@EnableWebMvc
を使用することができ、このようにSpringMVCはいくつかの自動構成を行う。具体的な自動構成内容はWebMvcConfigrationSupport類の定義を参照することができます。もちろん、WebMvcConfigrationSupportから直接継承して、一部の方法で書き換えてもいいです。@EnableWebMvc
@ComponentScan(basePackages = "com.elim.learn.spring.mvc.controller")
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
converters.add(new StringHttpMessageConverter(Charset.defaultCharset()));
}
}
AbstractAnnotationConfigDisplatServlet InitializerDisplatServletをweb.xmlファイルで定義しないでほしいなら、完全にプログラムで定義して、AbstractDisplatDisplatServletInitializerを定義するサブクラスを選択して、抽象的な方法を実現します。注解に基づく構成が必要であれば、直接にAbstractAnnotationConfigDisparer ServletInitializerクラスを継承することができる。AbstractAnnotationConfigDisplatServletInitializerでは、3つの抽象的な方法が定義されています。
getRootConfigClasses()
は、ルート構成のクラスを定義するために使用されています。すなわち、Appliation Contectの構成クラスに対応しています。もしこの構成がweb.xmlで構成されているなら、無視できます。getServletConfigClasses()
は、SpringMVCの構成クラスに対応する。getServletMappings()
は、マッピングが必要なアドレスを指定するために使用される。以下はカスタムの初期化類で、容器が起動した時に自動的に発見され、SpringMVCの初期化作業を行います。public class SpringInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return null;
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class>[]{MvcConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
(注:本文はSpring 4.1.0に基づいて書いています。)