Java学习笔记之SpringBoot篇

SpringBoot是什么?有什么用

SpringBoot是一个web开发框架,目的是为了简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用简单的语言描述来说就是Spring是一个“引擎”,SpringMVC则是一个基于Spring的MVC框架,而SpringBoot则是一个快速整合资源包。

@RestController和@Controller的区别

@RestController是指@Controller和@ResponseBody的结合体

  1. 两者的共同点:
    都是用来表示Spring某个类的是否可以接收HTTP请求;

  2. 两者的不同点:
    @Controller标识一个Spring类是baiSpring MVC controller处理器
    @RestController是一个便捷注释,仅添加@Controller和@ResponseBody注释

  3. 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。例如:本来应该到success.jsp页面的,则其显示success。

  4. 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。

  5. 如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

@RequestMapping

@RequestMapping作用:路由映射,用于类上做1级路径;用于某个方法上做子路径。

@GetMapping = @RequestMapping(method = RequestMethod.GET)		//获取
@PostMapping = @RequestMapping(method = RequestMethod.POST)		//提交
@PutMapping = @RequestMapping(method = RequestMethod.PUT)		//修改
@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)	//删除
注:如果不是细分PUT/DELETE方法,则可以都用POST

@SpringBootApplication

@SpringBootApplication 作用:用于标记是SpringBoot应用,里面包含多个子注解,即:

@SpringBootApplication =
@Configuration+@EnableAutoConfiguration+@ComponentScan

@Configuration: 主要标注在某个类上,⽤用于spring扫描注入,⼀一般结合@Bean使⽤

@EnableAutoConfiguration: 启用Spring的自动加载配置,自动载入应用程序所需的所有Bean

@ComponentScan:告诉spring扫描包的范围,默认是Applocation类所在的全部⼦子包,可以指定
其他包,例如:@ComponentScan({"net.xdclass.package1","net.xdclass.package2"})

SpringBoot配置Jackson处理字段

  1. 常用的框架:阿里fastJson ,谷歌gson等;
  2. JavaBean序列化为Json,
    性能:Jackson>FastJson>Gson>Json-lib同个结构
    Jackson、FastJson、Gson类库各有优点、各有自己的专长;
    空间换时间,时间换空间;
  3. JackSon处理相关自动
    指定字段不返回:@JsonIgnore
    指定日期格式:@JsonFormat(pattern=“yyyy-MM-dd hh:mm:ss”,locale=“zh”,timezone=“GMT+8”)
    空字段不返回:@JsonInclude(Include.NON_NULL)
    指定别名:@JsonProperty
  4. 开发功能:视频创建时间返回自定义格式;过滤用户敏感信息
  5. 序列化和反序列化操作
//序列话操作
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(list);
System.out.println(jsonStr);
//反序列列化操作
List<Video> temp = objectMapper.readValue(jsonStr,List.class);

SpringBoot2.x常见的配置文件形式 xml、yml、properties的区别和使用

常用的配置文件格式

xml、properties、json、yaml

SprintBoot里面常用xx.yml
yaml(Yet Another Markup Language);
写YAML要比写XML快得多(无需关注标签或引号)使用空格Space缩进表示分成,不同层次之间得缩进可以使用不用得空格数目;
注意:key后面得冒号,后面一定要跟一个空格,树状结构

使用@value注解配置文件自动映射到属性和实体类

配置文件加载
方式一:
- 1、Controller上面配置 @PropertySource({“classpath:resource.properties”})
- 2、增加属性 @Value("${test.name}") private String name;(配置类与实体所对应得名字)
方式二:
-1、添加 @Component 注解;
-2、使用 @PropertySource 注解指定配置文件位置;
-3、使用 @ConfigurationProperties 注解,设置相关属性;
-4、必须通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。
@Autowired private ServerSettings serverSettings;(@Autowired可以将类注入)

MockMvc测试方法

MockMvc的使用方法:
增加类注解@AutoConfigureMockMvc
注入一个MockMvc类
相关API:
perform执行一个RequestBuilder请求
angExpect:添加ResultMatcher–>MockMvcResuletMatchers验证规则
andReturn:最后返回相应的MvcResult–>Response
实例:

	@Autowired
	private MockMvc mockMvc;
	@Test
	public void testVideoListApi()throws Exception{
		MvcResult mvcResult =
		mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/pub/video/list"))
				.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
		int status = mvcResult.getResponse().getStatus();
		System.out.println(status);
		//会乱码
		//String result = mvcResult.getResponse().getContentAsString();
		// 使⽤用下⾯面这个,增加 编码 说明,就不不会乱码打印
		String result =
			mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));
		System.out.println(result);
}

Springboot2.X全局异常处理

简介:1、SpringBoot2.X全局异常处理(在设置前应完成配置Jackson处理字段)
- 配置好处:
统一的错误页面或错误码
对用户更加友好
- SpringBoot2.x怎么在项目中配置全局异常
类添加注解:
- @ControllerAdvice,如果需要返回json数据,则方法需要加@ResponseBody
- @RestControllerAdvice,默认返回Json数据,方法不需要加@ResponseBody
方法添加处理器
- 捕获全局异常,处理所有不可知的异常
- @ExceptionHandler(value=Exception.class) //添加需要捕获的异常类型
2、使用SpringBoot自定义异常和错误页面跳转
- 返回自定义界面,需要添加thymeleaf依赖(非必须,如果是简单的html界面则不用)
- resource⽬目录下新建templates,并新建error.html

ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;

thymeleaf

thymeleaf就是一种java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至是纯文本。类似于JSP和Freemarker,作用就是把各个用户的公用的东西(页面)做一个提取,然后再根据不同的数据对页面进行渲染。


#开发时关闭缓存,不不然没法看到实时⻚页⾯面
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#编码
spring.thymeleaf.encoding=UTF-8
#类型
spring.thymeleaf.content-type=text/html
#名称的后缀
spring.thymeleaf.suffix=.html

市面上的ORM框架

–1、hibernate(ssh)
比较笨重,sql调优麻烦,现在用的比较少,适合对数据库操作不多的项目
–2、JPA-Spring DATA JPA
Java Persistence API,轻量级,部分中小项目适用
–3、mybatis
半自动化(半ORM框架),便于写sql,轻量级,使用比较广泛

你可能感兴趣的:(Java学习笔记之SpringBoot篇)