spring boot java配置搭建ssm 小案例(IDEA)
1、创建Maven工程,在pom.xml文件上添加<packaging>war</packaging> 并且添加 spring-webmvc 的依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.javaboy</groupId> <artifactId>javassm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> </project>
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 class SpringConfig { }
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 implements WebApplicationInitializer { @Override public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setServletContext(servletContext); context.register(SpringMVCConfig.class); ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(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
@RestController public class HelloController { @Autowired HelloService helloService; @GetMapping(value = "/hello",produces = "text/html;charset=utf-8") public String hello(){ return helloService.hello(); } }
4、创建service
@Service public class HelloService { public String hello(){ return "你好!世界!"; } }
5、配置Tomcat,跟 spring boot xml配置搭建ssm 操作一样;最后,启动tomcat,访问http://localhost:8080/hello
此文章是通过个人搬砖汇总所得,用于个人复习。如有错误,麻烦指出,谢谢!