0%

SpringBoot常用注解

文章字数:835,阅读全文大约需要3分钟

一、配置相关

@springBootApplication
通常在主类上,包含:

  • @Configuration:表明是配置文件
  • @EnableAutoConfiguration:根据依赖自动配置springBoot
  • @ComponentScan:告诉Spring从哪里找bean(注解的包及下级包)

@Profiles
隔离应用程序配置,让配置在特定环境生效。
标注于@Component 或者 @Configuration

二、注入Bean

@Repository
标记数据库访问组件DAO。

@Service
标记业务层组件。

@RestController
标记控制层组件,包含:

  • @Controller:标记控制层组件
  • @ResponseBody:根据前端dataType将返回的对象转换成相应格式jsonxml

@Component
泛指组件,不好归类时标记

@Bean
在方法上使用,产生一个bean,交给spring

三、使用Bean

@AutoWired
自动注入,可以作用于成员变量、方法、构造方法。(required=false)找不到bean也不报错

@Qualifier
当AutoWired有多个同类型bean时(“name”)指定

@Resource(name=”name”,type=”type”):
没有括号内内容的话,默认byName。与@Autowired干类似的事。

四、网络请求相关

@RequestMapping
处理请求的地址映射,可在类与方法上。类上代表是方法上的父路径。
六个属性:

  • params:指定request中必须有某参数
  • headers:request中必须有指定的header
  • value:指定请求实际地址
  • method:指定类型,GET、POST….
  • consumes:指定处理提交类型(Content-Type),application/json,test/html等

@RequestParam
方法的参数前,获取指定名称的参数并传入形参(键值对类型的参数)

1
public User getUser(@RequestParam(value = "id", required = false) Integer id)

required=false表示该值可不存在,可为空。也可以作用于@Autowired表示该bean不是必须的,可不存在,可为空。

@PathVariable
路径变量,获取RequestMapping中占位符的值

1
2
3
4
@RequestMapping("/user/{uid}")
public String getUserById(@PathVariable Integer id){
//do something
}

@RequestBody
可以接收json格式的数据(应该可省略,直接写实体类目前可以直接转换)

1
public DbBook findBookByName(@RequestBody DbBook book)

接收字符串(不能组成一个实体类,所以不能用实体类接收的情况)

1
public void deleteBookById(@RequestBody Map<String, String> map)

@RequestBody接收不同的对象

  1. 创建一个新的entity,将两个entity都进去。
  2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。
  3. 实现自己的HandlerMethodArgumentResolver

@ModelAttribute
和实体类绑定

1
public String modelAttributeTest(@ModelAttribute User user)

注:multipart/form-data(二进制文件)@RequestBody不能处理这种格式的数据。
application/json、application/xml等格式的数据,必须使用@RequestBody来处理。

五、全局异常处理

@ControllerAdvice
control增强器

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
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import java.util.HashMap;
import java.util.Map;

/**
* controller 增强器,作用于所有有效的control
*/
@ControllerAdvice
public class MyControllerAdvice {

/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {}

/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Magical Sam");
}

/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}

}

@ExceptionHandler(Exception.class):
标注在方法上,遇到这个异常就执行以下方法

六、JPA

  • 建表时的附加语句,可以用来指定类型,默认值等
  1. tinyint类型的默认值@Column(name="state",columnDefinition="tinyint default 0")
  2. varchar(128),非空@Column(name = "Email",columnDefinition="varchar(128) not null")

当String类型不够用时可以指定属性在数据库中的类型为text

1
@Column(name = "Remark",columnDefinition="text")
  • uuid,见jpa主键生成策略

  • query执行sql语句

    1
    2
    3
    4
    5
     @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);

    @Query("select * from User u where u.name like :first and u.age>:age")
    List<User> findByNameLikeAndAgeGreaterThan(@Param("first")String firstName,@Param("age")Integer age);

七、值注入

  • @Value("${key}")

    通过key注入配置文件中的value

  • @Value("${myValue:#{null}}")注入非必填的
    @Value 想要非必填 required false

  • set上加

    1
    2
    3
    4
    @Value("${key}")
    public void setKeyvalue(String keyvalue){
    this.keyvalue=keyvalue;
    }
  • 构造方法注入

    1
    2
    3
    4
    5
    6
    class Message{
    private String text;
    Message(@Value("${app.text}") String text){
    this.text = text;
    }
    }