Spring各种注解

Spring

@ControllerAdvice

  • 类型:类注解

  • 位置:类

  • 作用:指定拦截哪些类,并且进行AOP增强

  • 属性

    • annotations:拦截加了这些注解的的类,并且进行增强

  • 范例

    @ResponseBody
    @ControllerAdvice(annotations = {RestController.class, Controller.class})
    @Slf4j
    public class GlobalExceptionHandler {
    ​
        /**
         * 异常处理方法
         * @param exception
         * @return
         */
        @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
        public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
            log.error(exception.getMessage());
            return R.error("出现异常!失败");
        }
    }

@ResponseBody

  • 类型:类 / 方法注解

  • 位置:类 / 方法

  • 作用:指定这个类中所有方法,或者本方法,返回给客户端一个JSON

  • 属性

    •  

  • 范例

    @ResponseBody
    @ControllerAdvice(annotations = {RestController.class, Controller.class})
    @Slf4j
    public class GlobalExceptionHandler {
    ​
        /**
         * 异常处理方法
         * @param exception
         * @return
         */
        @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
        public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
            log.error(exception.getMessage());
            return R.error("出现异常!失败");
        }
    }

@ExceptionHander

  • 类型:方法

  • 位置:方法

  • 作用:他修饰的方法进化为异常处理器,处理value中指定的异常

  • 属性

    • value:指定哪些异常会这个方法被处理

  • 范例

    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
        public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
            log.error(exception.getMessage());
            return R.error("出现异常!失败");
        }

##

@Configration

  • 类型:类注解

  • 位置:config/Spring配置类

  • 作用:标注这个类是一个配置类

  • 属性

    •  

  • 范例

    @Configration//配置类
    @MapperScan("mapper接口所在的包")//指定接口所在包
    public class MPConfig{
        
    }

@Bean

  • 类型:方法注解

  • 位置:可用在Configuration / Componet注解

  • 作用:相当于配置xml里的id,和所在类

    image-20220827164716156

  • 属性

    •  

  • 范例

    @Slf4j
    @Configuration
    @MapperScan("com.itheima.reggie.mapper")
    public class MybatisPlusConfig {
    ​
        //使用拦截器开启页码插件配件
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            log.info("拦截器已开启,页码插件准备完毕");
            return mybatisPlusInterceptor;
        }
    }

    PostConstruct注解:在当前类初始化完成之后再执行被这个修饰的方法

@PostConstruct

  • 类型:方法注解

  • 位置:方法上

  • 作用:在当前类初始化完成之后再执行被这个注解修饰的方法

  • 属性

    •  

  • 范例

##

boot启动类

@SpringBootApplication

  • 类型:类注解

  • 位置:boot的启动类上,位置位于com.xxx.项目名

  • 作用:启动boot

  • 属性

    •  

  • 范例

    @Slf4j
    @SpringBootApplication
    public class ReggieApplication {
        public static void main(String[] args) {
            SpringApplication.run(ReggieApplication.class, args);
            log.info("项目启动成功");
        }
    }
    ​

Controller

@RequestHeader

  • 类型:参数列表注解

  • 位置:在MVC接口的参数列表上

  • 作用:获取请求头指定的

  • 属性

    • value:需要的请求头

    • require:是否必传

  • 范例

    @GetMapping("/{id}")
        public User queryById(@PathVariable("id") Long id, @RequestHeader(value = "Truth", required = false) String truth) {
            return userService.queryById(id);
        }

@PathVariable用于

  • 类型:参数注解

  • 位置:参数列表

  • 作用:接受路径参数,使用{参数名称}描述路径参数,参数数量较少,可以采用@PathVariable接受,通常用于传递id值

  • 属性

    • value(默认):指定id值

  • 范例

    @RequestMapping(valuee = "/users/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getUserById(@PathVariable Integer id){
        
    }

@RestController

  • 类型:类注解

  • 位置:基于SpringMVC的RESTful开发控制器类定义上方

  • 作用:设置当前控制器类为RESTful风格,等同于@Controller与@ResponseBody两个组合注解功能

  • 属性

    • value(默认):请求访问路径,如果控制器方法中有别的控制器路径参数需要,保留类上的RequstMapping value = "/{路径参数}"

  • 范例

    @RestController(value = "/abc")
    public class BookController{
        @RequestMapping(value = "/{id}", method="RquestMethod.GET")
        public void getBookById(@PathVariable Integer id){
            
        }
    }

@GetMapping / @PostMapping / @PutMapping / @DeleteMapping

  • 类型:方法注解

  • 位置:基于SpringMVC的RESTful开发控制器方法上方

  • 作用:设置当前响应方法为get/post/put/delete

  • 属性

    • value(默认):请求访问路径参数

  • 范例

    @RestController(value = "/abc")
    public class BookController{
        @GetMapping("/{id}")
        public void getBookById(@PathVariable Integer id){
            
        }
    }

@Value读取yml数据中的单一数据

  • 类型:属性注解

  • 位置:放在属性的上方

  • 作用:获取对应yml中的数据内容

  • 属性

    • ${一级属性名.二级属性名}${一级属性名.二级数组属性名[下标]}

  • 范例

    image-20220823114208766

TEST

@SpringBootTest

  • 类型:类注解

  • 位置:在ApplicationTest类上,SpringBoot整合JUnit上

  • 作用:设置Junit加载的SpringBoot启动类,测试类如果存在于引导类所在包或者子包中无需指定类,如果不在使用classes属性配置即可

  • 属性:

    • classes:指定引导类(xxxApplication)的类名,相当于@SpringBootTest + @ContextConfiguration(classes = CommunityApplication.class)

  • 范例

    @SpringBootTest(classes = CommunityApplication.class)
    public class MapperTest {
        @Autowired
        private UserMapper userMapper;
    ​
        @Test
        public void testUserMapper(){
            User user = userMapper.selectById(101);
            System.out.println(user);
            User user1 = userMapper.selectByEmail("nowcoder11@sina.com");
            System.out.println(user1);
            User liubei = userMapper.selectByName("liubei");
            System.out.println(liubei);
        }
    }

 

Mybatis-plus

@TableName

  • 类型:类注解

  • 位置:pojo实体类类

  • 作用:标注实体类对应的数据库里的表名

  • 属性

    • value(默认):@TableName("表名")

  • 范例

    @TableName("t_user")
    public class User{
        
    }

@TableId

  • 类型:属性注解

  • 位置:pojo实体类属性的值上

  • 作用:修饰这个属性设置为主键

  • 属性

    • type:设置当前字段IdType.AUTO(自增,必须确保数据库设置了当前类自增,否则无效) / 为null / IdType.ASSIGN_ID(默认的,不写也行,通过雪花算法生成) IDtype类中有详解

    • value:当前字段,映射为数据库里主键的字段

  • 范例

    @TableName("t_user")
    public class User{
        @TableId(type = IdType.AUTO, value = "uid")//设置id字段为自增,在数据库中字段为uid
        private String id;
    }
  • @TableFileld

    • 类型:属性注解

    • 位置:pojo实体类属性

    • 作用:指定字段名为数据库表中的字段名

      1. 对象中属性名和字段名不一致的问题(非驼峰)

      2. 对象中的属性字段在表中不存在的问题

      3. 查询反不返回值

    • 属性

      • value(默认):@TableName(value = "字段名")

      • exist:true / false,这个字段在数据库表中存在 / 不存在

      • select:true / false,查询时不返回这个字段的值password常用

    • 范例

    @TableName("t_user")
    public class User{
         @TableName(value = "id")//设置字段名为id
        private String userId;
    }

@TableLogic

  • 类型:参数注解

  • 位置:位于实体类的参数上

  • 作用:设置这个参数为进行逻辑删除的字段

  • 设置一个int is_delete字段,意思就是进行逻辑删除,在实体类中设置这个类为@TableLogic的,那么你删除这个字段值的时候,就变成了修改is_delete为1,0为未删除

    那么查询的时候,就多了一个条件,查找is_delete 为0的,意思查找未删除的数据。

@MapperScan

  • 类型:类注解

  • 位置:MyBatis配置类

  • 作用:指出Mapper接口所在位置

  • 属性

    • value:Mapper接口所在包的全类名

  • 范例

    @Configration//配置类
    @MapperScan("mapper接口所在的包")//指定接口所在包
    public class MPConfig{
        
    }

日志

@Slf4j

  • 类型:类注解

  • 位置:放在类上

  • 作用:可以使用log日志

  • 属性

    •  

  • 范例

    @Slf4j
    @SpringBootApplication
    public class ReggieApplication {
        public static void main(String[] args) {
            SpringApplication.run(ReggieApplication.class, args);
            log.info();
        }
    }
    ​

Cloud

@LoadBalanced

  • 类型:方法注解

  • 位置:配置类的方法上,和bean一起用

  • 作用:代表让这个bean负载均衡

  • 属性

    •  

  • 范例

    /**
         * 创建RestTemplate并注入spirng容器
         */
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }

@Value

  • 类型:属性注解

  • 位置:属性

  • 作用:从配置文件中读取配置信息

  • 属性

    • defult:("${}"),填入对应你要读取的配置数据

  • 范例

    @Value(${pattern.dateformat})
    private String dateformat;

@RefreshScope

  • 类型:类注解

  • 位置:在@Value注入的变量所在类上添加

  • 作用:配置文件一旦发生更改,通知属性进行刷新配置信息

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    /**
     * kf 在配置管理中获取配置信息
     *
     */
    @Value("${pattern.dateformat}")
    private String dateformat;
​
    /**
     * km 按照从配置管理器中获取的规定的格式返回当前时间
     *
     * @return
     */
    @GetMapping("/now")
    public String now(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
    }
}

@ConfigurationProperties

  • 类型:类注解

  • 位置:配置类对应的属性的类

  • 作用:指定配置类中对应的属性的类,完成配置自动加载

  • 属性

    • prefix:前缀名,与类中的属性相拼接,得到application.yml文件里配置的属性的全名

  • 范例

    @Data
    @Component
    @ConfigurationProperties(prefix = "pattern")
    public class PatterProperties {
        private String dateformat;
    }

@FeignClient

  • 类型:接口注解

  • 位置:Feign客户端接口

  • 作用:声明Feign客户端

  • 属性

    • value(defult):需要开启Feign的服务名称

  • 范例

    @FeignClient("userservice")
    public interface UserClient {
    ​
        /**
         * km Feign远程调用接口 - userservice微服务
         * 
         * @param id
         * @return
         */
        @GetMapping("/user/{id}")
        User findUserFeign(@PathVariable("id") Long id);
    }
@EnableFeignClients
  • 类型:类注解

  • 位置:application启动类

  • 作用:开启Feign的功能

  • 属性

    • defultConfiguration:默认Feign配置类.class

    • basePackages: Feign单个模块时,FeignClient所在包的路径

    • clients:Feign单个模块时,FeignClient所在类的.class文件

  • 范例

@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients(clients = {UserClient.class}, defaultConfiguration = DefaultFeignConfiguration.class)
public class OrderApplication {
    //...
}

@Order

  • 类型:类注解

  • 位置:webflux过滤器类

  • 作用:标记过滤器的执行顺序,越小执行顺序越靠前,也可以让这个类实现Ordered接口,并且重写Order方法

  • 属性

    • default:整数类型,这个数越小,执行顺序越靠前,一般-1就代表最靠前

  • 范例

    @Order(-1)
    @Component
    public class AuthorizeFilter implements GlobalFilter {
        //。。。
    }
    //和下列写法一样
    @Component
    public class AuthorizeFilter implements GlobalFilter, Ordered{
        //。。。
        
        @Override
        public int getOrder() {
            return -1;
        }
    }

Security

@EnableGlobalMethodSecurity

  • 类型:类注解

  • 位置:SpringBoot配置类

  • 作用:开启Seq注解

  • 属性

    • prePostEnable:开启Seq方法全局注解

  • 范例

@MapperScan("com.sangeng.token.mapper")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class TokenApplication {
    public static void main(String[] args) {
        SpringApplication.run(TokenApplication.class,args);
    }
}

@PreAuthorize

  • 类型:方法

  • 位置:controller方法

  • 作用:访问目标之前,进行授权的认证,认证你是否能访问这个资源

  • 属性

    • 表达式:"是否有该权限('权限')" "hasAuthority('test')"

  • 范例

    @GetMapping("/hello")
    @PreAuthorize("hasAuthority('test')")
    public String hello() {
        return "hello";
    }

 

posted on 2022-10-04 14:33  老菜农  阅读(27)  评论(0编辑  收藏  举报

导航