1、创建Maven工程,在pom.xml文件上添加war 并且添加 spring-webmvc 的依赖
4.0.0
org.javaboy
javassm
1.0-SNAPSHOT
war
org.springframework
spring-webmvc
5.1.6.RELEASE
javax.servlet
javax.servlet-api
4.0.1
provided
2、创建两个配置类,SpringConfig.java 和 SpringMVCConfig.java,两个类分别都加上 @Configuration 注解(标明此类为配置类)和 @ComponentScan注解(指定扫描包的位置)
SpringConfig.java 对应 Spring 容器的配置
@Configuration
@ComponentScan(basePackages= "org.javaboy",useDefaultFilters = true,excludeFilters = {@ComponentScan.Filter(type =FilterType.ANNOTATION,classes= Controller.class)})public classSpringConfig {
}
SpringMVCConfig.java 对应 springMVC 容器的配置
@Configuration
@ComponentScan(basePackages= "org.javaboy",useDefaultFilters = false,includeFilters = {@ComponentScan.Filter(type =FilterType.ANNOTATION,classes= Controller.class),@ComponentScan.Filter(type =FilterType.ANNOTATION,classes= Configuration.class)} )public class SpringMVCConfig {
为什么 SpringMVCConfig.java 上的 @ComponentScan 注解包含有 @ComponentScan.Filter(type = FilterType.ANNOTATION,classes= Configuration.class)
因为创建好这两个配置类后,需要再创建一个类来加载它们,那就创建一个WebInit.java 并实现WebApplicationInitializer 接口,此处所做的事情就是 web.xml 所做的一样
public class WebInit implementsWebApplicationInitializer {
@Overridepublic void onStartup(javax.servlet.ServletContext servletContext) throwsServletException {
AnnotationConfigWebApplicationContext context= newAnnotationConfigWebApplicationContext();
context.setServletContext(servletContext);
context.register(SpringMVCConfig.class);
ServletRegistration.Dynamic springmvc= servletContext.addServlet("springmvc", newDispatcherServlet(context));
springmvc.addMapping("/");
springmvc.setLoadOnStartup(1);
}
}
此类只加载了一个 SpringMVCConfig.java , 而 SpringConfig.java 没有被加载,但是,在 SpringMVCConfig.java 上的 @ComponentScan 注解包含有 @ComponentScan.Filter(type = FilterType.ANNOTATION,classes= Configuration.class)
所以 SpringConfig.java 的加载可以通过先加载 SpringMVCConfig.java ,再加载包含有 @Configuration 注解的类。
3、创建controller
@RestControllerpublic classHelloController {
@Autowired
HelloService helloService;
@GetMapping(value= "/hello",produces = "text/html;charset=utf-8")publicString hello(){returnhelloService.hello();
}
}
4、创建service
@Servicepublic classHelloService {publicString hello(){return "你好!世界!";
}
}
5、配置Tomcat,跟 spring boot xml配置搭建ssm 操作一样;最后,启动tomcat,访问http://localhost:8080/hello
此文章是通过个人搬砖汇总所得,用于个人复习。如有错误,麻烦指出,谢谢!