java注解

@Target({ElementType.METHOD, ElementType.TYPE})

注解的适用范围,可以用在什么地方,超过这个作用范围,编译的时候就会报错

说明
ElementType.METHOD用于描述方法
ElementType.TYPE用于描述类、接口(包括注解类型) 或enum声明
ElementType.LOCAL_VARIABLE用于描述局部变量
ElementType.PARAMETER用于描述参数
ElementType.CONSTRUCTOR用于描述构造器
ElementType.FIELD用于描述域
ElementType.PACKAGE用于描述包

@Retention(RetentionPolicy.SOURCE)

用来修饰注解的,表示注解的生命周期

取值描述作用范围使用场景
RetentionPolicy.SOURCE表示注解只保留在源文件,当java文件编译成class文件,就会消失源文件只是做一些检查性的操作,,比如 @Override 和 @SuppressWarnings
RetentionPolicy.CLASS注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期class文件(默认)要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife)
RetentionPolicy.RUNTIME注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在运行时也存在需要在运行时去动态获取注解信息

lombok的全参构造函数为例,它的声明周期是源文件
在这里插入图片描述
这个注解作用是全参构造函数,可以看到编译后这个注解没了,多了全参构造函数
在这里插入图片描述

值校验注解

@NotEmpty、@NotBlank、@NotNull 区别和使用

来源:http://t.csdn.cn/Pp1N1

1:引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>

@NotEmpty、@NotBlank、@NotNull 包的位置:

import javax.validation.constraints.*;

2:区别

@NotNull

适用于基本数据类型(Integer,Long,Double等等),当 @NotNull 注解被使用在 String 类型的数据上,则表示该数据不能为 Null(但是可以为 Empty)

注:被其标注的字段可以使用 @size、@Max、@Min 对字段数值进行大小的控制

@NotBlank
适用于 String 类型的数据上,加了@NotBlank 注解的参数不能为 Null 且 trim() 之后 size > 0,必须有实际字符

@NotEmpty
适用于 String、Collection集合、Map、数组等等,加了@NotEmpty 注解的参数不能为 Null 或者 长度为 0

3:使用方法

@Data
public class BigPeople {
    @ApiModelProperty(value = "id" ,required = true)
    @NotNull(message = "id不能为空")
    @Length(message = "id不能超过{max}个长度",max = 10)
    private Integer id;
 
    @ApiModelProperty(value = "name" ,required = true)
    @NotBlank(message = "name不能为空")
    @Size(message = "名字最长为{max} 个字",max = 10)
    private String name;
 
    @ApiModelProperty(value = "age" ,required = true)
    @NotNull(message = "id不能为空")
    @Range(message = "age的长度范围为{min}岁到{max}岁之间",min = 5,max = 10)
    private Integer age;
 
    @ApiModelProperty(value = "treeNode" ,required = true)
    @NotEmpty(message = "treeNode不能为空")
    private List<String> treeNode;
    
}

@Valid 包位置:

import javax.validation.Valid;

@Validated 包的位置

import org.springframework.validation.annotation.Validated;
    @ApiOperation(value = "新增或者修改一个人的信息")
    @PostMapping("/updateOrInsert")
    public Result updateOrInsert(@Valid @RequestBody  Person person){
        Boolean updateOrInsert = personService.updateOrInsert(person);
        if (updateOrInsert) {
            return new Result(ResultCode.SUCCESS,updateOrInsert);
        }
       return new Result(ResultCode.ERROR, "新增或者修改一个人的信息失败");
    }
 
 
  
    @ApiOperation(value = "新增或者修改一个人的信息")
    @PostMapping("/updateOrInsert")
    public Result updateOrInsert(@Validated @RequestBody  Person person){
        Boolean updateOrInsert = personService.updateOrInsert(person);
        if (updateOrInsert) {
            return new Result(ResultCode.SUCCESS,updateOrInsert);
        }
       return new Result(ResultCode.ERROR, "新增或者修改一个人的信息失败");
    }

最上面三个注释: 必须需要搭配@Valid 或者@Validated使用,在检验Controller的入参是否符合规范时

@Valid 和 @Validated 比较

1:@Valid 和 @Validated 两者都可以对数据进行校验,待校验字段上打的规则注解(@NotNull, @NotEmpty等)都可以对 @Valid 和 @Validated 生效;

2:@Valid 进行校验的时候,需要用 BindingResult 来做一个校验结果接收。当校验不通过的时候,如果手动不 return ,则并不会阻止程序的执行;

3:@Validated 进行校验的时候,当校验不通过的时候,程序会抛出400异常,阻止方法中的代码执行,这时需要再写一个全局校验异常捕获处理类,然后返回校验提示。

4:总体来说,@Validated 使用起来要比 @Valid 方便一些,它可以帮我们节省一定的代码,并且使得方法看上去更加的简洁。

此包下其它常用的校验注解:

注解含义
@Null元素必须为null
@NotNull元素不能null
@AssertTrue元素必须为true
@AssertFalse元素必须是false
@Min(value)元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min)元素的大小必须在指定的范围内
@Digits(integer,fraction)元素必须是一个数字,其值必须在可接受的范围内
@Past元素必须是一个过去的日期
@Future元素必须是一个将来的日期
@Pattern(value)元素必须符合指定的正则表达式

@Email

@Length

@NotEmpty

@Range

1:元素必须是电子邮箱地址

2:字符串的大小必须在指定的范围内

3:字符串必须非空

4:元素必须在合理的范围内

@NoRepositoryBean

使用了该注解的接口不会被单独创建实例,只会作为其他接口的父接口而被使用

@PathVariable

RESTful , 取URL的参数,@PathVariable 注解将 URL 中的路径参数username绑定到方法的参数username上

// 如果写成:/test?username=123   报错
// 只能写成:/test1/123 
//后端:
	//如果@PathVariable("username")的名称和参数 String name的一样,就可以不用写@PathVariable的参数,写成public String test1(@PathVariable("username") String name){
    @RequestMapping("/test1/{username}")
    public String test1(@PathVariable("username") String name){
        
        if(StringUtils.isNotBlank(name)){
            return name;
        }

        return "null";
    }

@RequestParam

url中参数绑定到方法参数上

//URL:/test/test1?name=zhangsan    ,如果url:/test1/123会报错
    @RequestMapping("/test1")
    public String test1(@RequestParam String name){

        if(StringUtils.isNotBlank(name)){
            return name;
        }

        return "null";
    }

有很多种写法

1.@RequestParam(value="id",required = true/false)	//写参数名和是否非空
 
2.@RequestParam(value="id")    //可以非空不写,默认required = true
 
3.@RequestParam("id")     //只有一个参数,可以value省略掉
 
4.@RequestParam		//如果参数名一样,可以不写参数
 
5.省略不写注解 @RequestParam		//参数名一致,也可以直接不写
@GetMapping 配合 @RequestParam@RequestBody@PathVariable;
@PostMapping 配合 @RequestBody (使用@RequestParam很有可能debug失效或者获取不到参数数据)
 
@RequestParam:对包装类,基本类型,String等通过属性value指定参数名
@RequestBody:对对象,MapList等直接使用
@PathVariable:配合属性value使用,来匹配url中的占位符

@RequestBody

绑定对象参数用的,

  • 如果是form表单提交,不用写@RequestBody,springmvc自动将表单数据绑定到controller方法的参数上,

  • 如果你写了@RequestBody,就会去请求体取数据,而不是从form中

    • 没有设置required = false,不管form提交是不是空,但是请求体是空的,会报错
    • 没有设置required = false,请求体不为空,form也不为空,获取的是请求体的数据
  • 表单提交,不用写@RequestBody

        @RequestMapping("/test1")
        public String test1(Users user){
    
            String name=user.getUsername();
    
            if(StringUtils.isNotBlank(name)){
                return name;
            }
    
            return "null";
        }
    

    在这里插入图片描述

  • 请求体提交

        @RequestMapping("/test1")
        public String test1(@RequestBody Users user){
    
            String name=user.getUsername();
    
            if(StringUtils.isNotBlank(name)){
                return name;
            }
    
            return "null";
        }
    

    在这里插入图片描述

  • post接口需要使用@RequestBody才能正确获取到参数,get接口不用

POST请求:参数通常是通过请求体(request body)传递的,例如JSON格式的数据。在Spring Boot中,如果想要正确地获取POST请求的参数,需要使用@RequestBody注解来告诉Spring Boot将请求体中的数据映射到方法的参数上。

而对于GET请求,Spring Boot会自动解析URL中的查询字符串,无需使用@RequestBody注解。

@ResponseBody

不会解析为路径条件,例如返回请求为JSON的时候

@Param

mybatis中用来绑定参数名称的,如果方法入参和sql中的参数名称不符,就使用@Param

public User getUser(@Param("userName") String name,String id);
<select id="getUser" resultMap="User">  
   select * from user  where user_name = #{userName} and user_id=#{id}  
</select>

@ModelAttribute

@ModelAttribute与@RequestBody都是用来注解解析前端发来数据,并自动对应到所定义的字段名称。

@ModelAttribute注解的实体类接收前端发来的数据格式需要为"x-www-form-urlencoded",
@RequestBody注解的实体类接收前端的数据格式为JSON(application/json)格式。(若是使用@ModelAttribute接收application/json格式,虽然不会报错,但是值并不会自动填入)

注册条件

@ConditionalOnBean

条件注解,符合这些条件,被该注解修饰的类或方法才能生效。

    @Bean
    @ConditionalOnBean(Emp.class)	//如果容器中存在Emp这个Bean,才会执行
    public User (User user) {

        return new User("zhangsan");
    }

@ConditionalOnProperty

配置文件中存在对应的属性,才声明该Bean

    //配置文件中,有前缀为person,并属性同时有name和age,就注入这个Bean,否则不注入
    @ConditionalOnProperty(prefix = "person", name={"name","age"})
    @Bean
    public User user(@Value("${person.name}") String name,@Value("pwd") String pwd){
        System.out.println("name:"+name+",pwd:"+pwd);
        return new User();
    }

@ConditionalOnMissingBean

不存在指定bean,才会创建该Bean

    //IOC容器中没有User这个Bean,就注入这个dept这个bean
    @ConditionalOnMissingBean(User.class)
    @Bean
    public Dept dept(){
        return new Dept();
    }

@ConditionalOnClass

如果当前环境有User这个类,就注入Dept

    //IOC容器中有User这个Bean,就注入这个dept这个bean
    @ConditionalOnClass(User.class)
    public Dept dept(){
        return new Dept();
    }

@PostConstruct

@PostConstruct 注解用于项目启动,在 bean 初始化完成后执行,通常用于在 bean 初始化完成后进行一些初始化操作。
和static{}的区别是,static{}只能用于初始化静态变量赋值,或者执行类中的静态方法;

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // 执行一些初始化操作
    }
}

当 Spring 容器初始化 MyBean 时,会在 MyBean 的所有属性都被设置完成后,执行 init() 方法。
@PostConstruct 注解是 Java 5 引入的,它可以用来替代 init-method 属性。init-method 属性是
Spring 2.5 之前使用的,它可以指定 bean 的初始化方法。 @PostConstruct 注解和 init-method
属性的区别在于,@PostConstruct 注解可以指定多个初始化方法,而 init-method 属性只能指定一个初始化方法。
此外,@PostConstruct 注解可以应用于任何类型的 bean,而 init-method 属性只能应用于被 @Component
或 @Service 或 @Controller 注解的 bean。

在系统启动即执行的执行顺序(适用于spring的类初始化加载场景,如果是普通类,单纯的去实例化这个类,@PostConstruct、CommandLineRunner不会起作用):static{}> Constructor > @Autowired > @PostConstruct> CommandLineRunner

获取配置文件值的方式

@ConfigurationProperties(prefix = “aliyun.oss.file”)

是一个Java注解,用于将配置文件中以"aliyun.oss.file"为前缀的属性绑定到一个Java对象上。这样可以通过该对象直接访问配置文件中的属性值,相当于这个效果,但是要有getset方法,不然是空值
在这里插入图片描述

@Value

用来读取配置文件中的值
用来修饰变量

@Value("${aliyun.oss.file.endpoint}")

在这里插入图片描述
也可以用在方法参数上

    @Bean
    public User user(@Value("${person.name}") String name,@Value("pwd") String pwd){
        System.out.println("name:"+name+",pwd:"+pwd);
        return new User();
    }

全局异常处理、跨切面关注点(如数据校验)以及模型属性添加的注解

@ControllerAdvice

标记一个类,使其成为适用于所有 @Controller 类型控制器的全局异常处理器或模型属性添加器。它主要用于传统 MVC 控制器,这些控制器通常返回视图名称或模型及视图对象。

@RestControllerAdvice

与 @ControllerAdvice 类似,但它专为 @RestController 设计。@RestController 类通常用于 RESTful Web 服务,它们直接返回数据对象,而不是视图。@RestControllerAdvice 可以处理异常,并返回 JSON 或 XML 等数据格式的响应。

@Bean

Spring 框架中的一个注解,用于在配置类中定义和注册 bean.替代 XML 配置文件中的 元素,在一个配置类中使用 @Bean 注解的方法时,该方法的返回值会被注册为 Spring 应用上下文中的一个 bean。简单说就是将注解的方法,注入到IOC中,

@Configuration
public class AppConfig {

	//默认名称就是myService,也可以用name指定
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

如果方法的内部需要使用IOC容器中已经存在的bean对象,只需要在入参写上,spring会自动注入

@Bean
public User user(){
	return new User();
}

//这个参数user就是上面注入的bean
@Bean Dept dept(User user){
	return new Dept();
}

@Import

可以导入任意类,不过最常用导入两种

导入配置类

如果配置类所在的包不在启动类所在的包,及其子包,那么spring是扫不到它的,使用@Import来导入配置类,就能注入到IOC容器中。并且,可以不用@Configuration,用@Configuration的意义就是告诉spring,我要将这个配置类加入到IOC中,既然扫不到了,通过@Import手动导入,自然@Configuration没用了。

//手动导入SpringBootConfig类
@Import(SpringBootConfig.class)
@SpringBootApplication
public class SpringboottestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringboottestApplication.class, args);

    }
}

导入ImportSelector接口实现类

@Import可以导入单个类,也可以通过数组的形式导入多个类@Import({User.class,Dept.class..........}),但是如果太多的话,就会不太雅观。可以通过实现接口ImportSelector,重写selectImports方法,

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class SpringbootImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    	//返回一个数组对象,要类的包路径
        return new String[]{"com.wzw.config.SpringBootConfig"};
    }
}

实现完以后,要通过@Import在启动类导入这个类,或者在这个实现类上使用@Configuration,让它加入IOC容器中。
实现ImportSelector接口的这种方式,再优化一下,参数不要手动写,而是从*.imports文件中读取,这个*.imports放在resourse下面,整个实现有点像自动配置的原理,很多包下面都有以imports结尾的文件,他们的自动配置就是这么实现的通过ImportSelector这么实现的。

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SpringbootImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //创建要添加到容器中的对象
        List<String> list=new ArrayList<>();
        //使用imputstream读取config.imports配置文件
        InputStream inputStream = SpringbootImportSelector.class.getClassLoader().getResourceAsStream("config.imports");
        //创建bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            //每行的内容
            String line=null;
            //读取每一行,每一行就是一个类的全路径
            while ((line=bufferedReader.readLine())!=null){
                //类的全路径添加到list中
                list.add(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        //list转成String数组,就跟前面的return new String[]{"com.wzw.config.SpringBootConfig"}一样格式
        return list.toArray(new String[0]);
    }
}

fastjson的注解

@JsonIgnore

忽略字段,不返回给前端

public class User{
	
	@JsonIgnore
    private String name;
.......
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值