Spring/SpringBoot 知识点整理
package com.example.restservice; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @GetMapping("/greeting") public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
@RestController @RequestMapping(value="/users") public class MyRestController { @RequestMapping(value="/{user}", method=RequestMethod.GET) public User getUser(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}/customers", method=RequestMethod.GET) List<Customer> getUserCustomers(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}", method=RequestMethod.DELETE) public User deleteUser(@PathVariable Long user) { // ... } }
1.GetMapping对应@RequestMapping(method=GET)
2.@RequestParam 绑定单个参数,可以有默认值,即defaultValue
3.@RestController 使得每个方法返回的都是个domain object,不能是view,也就是将该对象直接转为Json输出,通常由Jackson 2 自动进行对象到json转换,这是自动处理的。
这等同于@Controller,@ResponseBody(加到方法上)两者结合的效果
2. 打包
package一个完整的jar,可独立运行的jar(所有的类放置到一个jar中,包含依赖的所有jar,不同于fatjar这种机制,spring的是把jar都放置到jar的lib目录里,这样能更好的看到依赖哪些jar文件)
pom.xml增加:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
运行mvn package即可,注意这个配置如果是在多个module时,必须在有@SpringBootApplication配置的module下使用,否则会报错。
3.使用xml配置,有可能某些特殊情况
通过@ImportResource 实现:https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-structuring-your-code
4.自动注册spring bean的组件
@Component, @Service, @Repository, @Controller等
5.SpringBoot 2.4 最新版文档里写到SpringBoot启动时支持懒加载,有时间试试,之前的SpringBoot 2.1.4没有这个方法,在独立启动时有用,能加快程序启动速度,有时间试试
增加配置项:
spring.main.lazy-initialization=true
或者调用SpringApplication的setLazyInitialization 方法。
6.SpringMVC :https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
7.spring url正则匹配规则:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping-uri-templates
-
"/resources/ima?e.png"
- match one character in a path segment -
"/resources/*.png"
- match zero or more characters in a path segment -
"/resources/**"
- match multiple path segments -
"/projects/{project}/versions"
- match a path segment and capture it as a variable -
"/projects/{project:[a-z]+}/versions"
- match and capture a variable with a regex
8.Spring 将new Object 整合进IOC进行管理
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
AppConfig可通过@Configuration或@Component标记,对应MyService方法通过@Bean表示,这样这种特殊需要new出来的对象也能被其他地方引用了,类似工厂模式吧。
此时等同于通过xml定义一个bean:
<beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans>
9.Spring MVC配置跨域请求
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://domain2.com") .allowedMethods("PUT", "DELETE") .allowedHeaders("header1", "header2", "header3") .exposedHeaders("header1", "header2") .allowCredentials(true).maxAge(3600); // Add more mappings... } }
或者用xml
mvc:cors> <mvc:mapping path="/api/**" allowed-origins="https://domain1.com, https://domain2.com" allowed-methods="GET, PUT" allowed-headers="header1, header2, header3" exposed-headers="header1, header2" allow-credentials="true" max-age="123" /> <mvc:mapping path="/resources/**" allowed-origins="https://domain1.com" /> </mvc:cors>
10.Message Converters
可以自定义ResponseBody转换输出的xml格式等
@Configuration @EnableWebMvc public class WebConfiguration implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder() .indentOutput(true) .dateFormat(new SimpleDateFormat("yyyy-MM-dd")) .modulesToInstall(new ParameterNamesModule()); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); } }
文档专门讲解Spring WebMvcConfigurer配置的,非常详细:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config
publicclass WebConfig implements WebMvcConfigurer { public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://domain2.com") .allowedMethods("PUT", "DELETE") .allowedHeaders("header1", "header2", "header3") .exposedHeaders("header1", "header2") .allowCredentials(true).maxAge(3600); // Add more mappings... } }
(11) 通过Spring初始化工厂
@Component public class ShiroTagFreeMarkerConfigurer implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { //初试话时调用该方法,可做基础配置 } }
方法2:
@Component public class ShiroTagFreeMarkerConfigurer{ @Autowired private Configuration configuration; @Autowired private FreeMarkerViewResolver resolver; @PostConstruct public void setSharedVariable(){ //初始化系统调用,只调用一次,spring会扫描@postconstruct进行处理 } }
关于Controller异常的处理
1.对于method抛出的异常,此时可以单独定义类来处理
@RestControllerAdvice public class ControllerExceptionHandler { @ExceptionHandler(value = Exception.class) public String handException(Exception e, HttpServletRequest request, HttpServletResponse response) { ...
在handException中可以返回JSON对象或者读取对应的错误文件内容通过response输出都可以。
2.对于框架层面的错误提示,比如spring抛出的404、500错误
参考:https://www.jb51.net/article/11835.htm