Bean处理

依赖注入

  • @Autowired: 用在属性和方法上。依赖注入,把配置好的bean拿来用
  • @Resource:默认情况下@Resource按照名称注入,如果没有显式声明名称则按照变量名称或者方法中对应的参数名称进行注入
  • @Qualifier:

标注类被Spring容器管理

  • @Component:组件,当组件不好归类的时候使用
  • @Respository:持久层,用于DAO类
  • @Service:服务层,用于Service类,通常需要注入DAO层
  • @Controller:MVC控制层Bean,常需要注入Service层
  • @RestController:继承@Controller注解,用于开发REST服务,直接将返回值当作json格式,通过body来给他返回。在使用 @RestController 注解标记的类中,每个方法的返回值都会以 JSON 或 XML 的形式直接写入 HTTP 响应体中,相当于在每个方法上都添加了 @ResponseBody 注解
  • @Configuration:声明配置类

声明Bean的生命周期

  • @Scope:singleton(单例)、prototype(多例, 每次获取Bean的时候会有一个新的实例)、request(每一次HTTP请求都会产生一个新的bean)、session(每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效)

HTTP请求

  • @GetMapping:GET请求,从服务器获取资源
  • @PostMapping: POST请求,创建资源
  • PutMapping:PUT请求,更新资源
  • DeleteMapping:DELETE请求,删除资源
1
2
3
4
5
6
7
8
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}

前后端参数传递

  • @RequestParam:通过表单获取参数置,用在方法的参数前面,获取请求中表单类型的key=value格式的数据
  • @PathVariable:路径变量,参数与大括号里的名字一样
  • @RequestBody:获取请求Body中的数据,用于搭配@PostMaping请求来提交数据
  • @ResponseBody:表示该方法的返回结果直接写入HTTP response body中,格式为json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@Controller
@RequestMapping("hello")
public class HelloController2 {

/**
* 接收普通请求参数
* http://localhost:8080/hello/show16?name=linuxsir
* url参数中的name必须要和@RequestParam("name")一致
* @return
*/
@RequestMapping("show16")
public ModelAndView test16(@RequestParam("name")String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通的请求参数:" + name);
return mv;
}

/**
* 接收普通请求参数,required=false(默认是true)
* http://localhost:8080/hello/show17
* url中没有name参数不会报错、有就显示出来
* @return
*/
@RequestMapping("show17")
public ModelAndView test17(@RequestParam(value="name",required=false)String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通请求参数:" + name);
return mv;
}

/**
* 接收普通请求参数
* http://localhost:8080/hello/show18?name=998 显示为998
* http://localhost:8080/hello/show18?name 显示为hello
* @return
*/
@RequestMapping("show18")
public ModelAndView test18(@RequestParam(value="name",required=true,defaultValue="hello")String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通请求参数:" + name);
return mv;
}
}

读取配置

  • @PropertySource:指定加载自定义的配置类路径
  • @Value:直接读取各种配置源的属性名
  • @Configuration:用于类上,表示配置类并与Bean绑定, @Configuration注解通常与@ComponentScan注解一起使用,用于扫描指定包中的组件
1
2
3
4
5
6
7
8
9
10
@PropertySource({"配置文件路径1","配置文件路径2"...})

@Value("${配置文件中的key:默认值}")
@Value("${配置文件中的key}")

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
// Bean定义
}

参数校验

  • Bean字段验证注解:比如@Email
  • @Valid:用于标注验证对象的级联属性
  • @Vliddated:标注方法参数需要检查

统一异常处理

  • ControllerAdvice:定义异常处理类,包括@Component,所以可以被Spring扫描到
  • ExceptionHandler:声明异常处理方法,表示遇到这个异常,就执行标注的方法
1
2
3
4
5
6
7
8
9
10
//@ControllerAdvice 配合 @ExceptionHandler 实现全局异常处理,@ExceptionHandler注解中可以添加参数,参数是某个异常类的class,代表这个方法专门处理该类异常
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ModelAndView handleException(IllegalArgumentException e){
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage", "参数不符合规范!");
return modelAndView;
}
}

JPA数据持久化

  • @Entity:声明数据库实体类。class 名即数据库表中表名,class 字段名即表中的字段名
  • Table:当实体类与其映射的数据库表名不同名时需要使用 @Table注解说明,该标注与 @Entity 注解并列使用,置于实体类声明语句之前,可写于单独语句行,也可与声明语句同行
  • Id:声明一个字段为主键
  • GeneraterValue:声明主键的生成策略,比如IDENTITY表示主键自增长
  • Column:声明主段,表示Java属性与表字段的映射关系
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Entity
@Table(name = "xwj_user", schema = "test")
public class UserEntity {

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "ID", unique = true, nullable = false, length = 32)
private Integer id;

@Column(name = "last_name")
private String lastName;

@Column(name = "email", length = 32)
private String email;

//TODO get和set方法略...
}

JSON格式处理

  • JsonIgnoreProperties:作用在类上用于过滤特定字段不返回
  • JsonIgnore:用于属性上表示不返回
  • JsonFormat:格式化json
  • JsonUnwrapped:扁平化对象

测试处理

  • @ActiveProfiles:用于测试类上
  • @Test:声明一个方法是测试方法
  • @Transactional:被声明的测试方法会回滚,避免污染测试
1
2
3
4
5
6
7
8
//常见的使用方式:使用rollbackFor 属性来定义回滚的异常类型,使用 propagation 属性定义事务的传播行为
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void processPayment(Order order) throws Exception {
// 如果抛出 Exception 或其子类的异常,将回滚事务
if (paymentFailed()) {
throw new Exception("Payment failed");
}
}

配置启动

  • @SpringBootApplication:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan的组合
  • @SpringBootConfiguration:SpringBoot的配置类
  • @EnableAutoConfiguration:用在类上,表示SpringBoot根据添加的jar依赖猜测你想如何配置Spring
  • @ComponentScan:定义哪些路径下的jar包被扫描
  • @Conditional:比如@ConditionalOnBean是配置某个特定的Bean