Spring MVC 注解配置 - 用注解替代 XML 配置
Spring MVC 注解配置:用注解替代 XML 配置
为了用注解替换 XML 配置,你需要对提供的 XML 配置进行以下更改:
-
删除
<servlet>和<servlet-mapping>元素。 -
在你的 Spring 配置类(通常命名为
WebConfig)中添加@Configuration注解。 -
添加
@EnableWebMvc注解以启用 Spring MVC 功能。 -
添加
@ComponentScan注解以指定用于扫描组件(例如控制器)的基本包。 -
修改
dispatcherServletbean 的声明,在你的WebConfig类中使用@Bean注解。
以下是使用注解修改后的配置示例:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = 'com.example.controller')
public class WebConfig implements WebMvcConfigurer {
@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp().prefix('/WEB-INF/views/').suffix('.jsp');
}
}
确保将 'com.example.controller' 替换为你的控制器的适当基本包。
请注意,根据你的应用程序需求,你还需要配置其他方面,例如视图解析器、资源处理等。
原文地址: https://www.cveoy.top/t/topic/qyJJ 著作权归作者所有。请勿转载和采集!