Java常用 @注解

张开发
2026/4/8 4:29:26 15 分钟阅读

分享文章

Java常用 @注解
JsonProperty注解JsonProperty 是 Jackson 库中的一个注解用于控制 Java 对象与 JSON 数据之间的序列化和反序列化过程。该注解被用来指定某些字段在 JSON 表示时应使用的属性名JsonProperty(hotel_id) private String hotelId;Async注解当一个方法被 Async 注解修饰时该方法会在独立的线程中执行而不会阻塞调用者线程。适用于需要长时间运行的任务例如发送邮件、处理文件、调用外部服务等以避免主线程等待这些任务完成。Async 注解表明该方法将异步执行Scope(prototype)可以通知Spring把被注解的Bean变成多例Primary注解意思是在众多相同的bean中,优先使用用Primary注解的beanJSONField注解fastjson中的注解JSONField(ordinal 0) 序列化字段的顺序默认是0JSONField(name “”) 用于解决属性名和key不一致的情况当前端传过来的字段名不一样的时候我们可以在字段名上加上这个注解JSONField(format “yyyy-MM-dd HH:mm:ss”) 用在Date属性上自动格式化日期JSONField(serialize false) 是否要把这个字段序列化成JSON字符串默认是trueJSONField(deserialize false) 字段是否需要进行反序列化默认是truePostConstruct注解PostConstruct注解的方法在项目启动的时候执行这个方法也可以理解为在spring容器启动的时候执行可作为一些数据的常规化加载比如数据字典之类的。Param注解public User selectUser(Param(userName) String name,Param(password) String pwd);映射到xml中的select标签select idselectUser resultMapUser select * from user where user_name #{userName} and user_password#{password} /select注意点当使用了Param注解来声明参数的时候SQL语句取值使用#{}${}取值都可以。当不使用Param注解声明参数的时候必须使用的是#{}来取参数。使用${}方式取值会报错。不使用Param注解时参数只能有一个并且是Javabean。在SQL语句里可以引用JavaBean的属性而且只能引用JavaBean的属性。Select(SELECT * from Table where id #{id}) Enchashment selectUserById(User user);Scheduled注解作用spring定时器(定时执行一次或定时轮询执行一段代码) 。启动类上加 EnableScheduling 注解该参数接收一个cron表达式cron表达式是一个字符串字符串以5或6个空格隔开分开共6或7个域每一个域代表一个含义。[秒] [分] [小时] [日] [月] [周] [年]示例#每天23:59:00执行一次 Scheduled(cron 0 59 23 * * ?) #每两分钟执行一次 Scheduled(cron 0 0/2 * * * ? ) Scheduled(cron${accountExpire.cron})Profile(xx) 注解当 Spring 启动时会检查当前激活的 profile。Profile(dev)只有当 spring.profiles.activedev 时才会被注册为 BeanProfile(!prod) // 这样在除了生产环境外的所有环境都会启用日志切面 Profile({dev, test, local}) // 明确指定在开发相关环境中启用JsonInclude 注解jackson自动序列化时忽略所有值为 null 的字段{ code: 2, message: 授权数不足当前剩余授权数为980无法再分配1980个坐席, agentCount: null, // ❌ 多余的 null 字段 agentRemain: null, // ❌ 多余的 null 字段 agentLimit: null // ❌ 多余的 null 字段 }Value注解使用Value方式获取application配置文件中参数application.yml中配置test: msg: hello springboot使用Value方式import org.springframework.beans.factory.annotation.Value; RestController Component public class WebController { Value(${test.msg}) private String msg; //假设 app.languagesen,fr,de则 languages 列表将包含 [en, fr, de] Value(#{${app.languages}.split(,)}) private ListString languages; //文件中没有定义 app.name则使用默认值 defaultAppName Value(${app.name:defaultAppName}) private String appName; //可以注入复杂对象例如 Properties 或 Map。 Value(#{${app.properties}}) private Properties appProperties; Value(#{${app.map}}) private MapString, Object appMap; RequestMapping(/index1) public String index1() { return 方式一: msg; } } //Value注入static属性 private static String name; Value(${person.name}) private String s; PostConstruct public void init() { name s; } //Java中该注解的说明PostConstruct该注解被用来修饰一个非静态的void方法。被PostConstruct修饰的方法会在服务器加载Servlet的时候运行并且只会被服务器执行一次。PostConstruct在构造函数之后执行init方法之前执行。 Constructor(构造方法) - Autowired(依赖注入) - PostConstruct(注释的方法)类不能用new通过Autowired 方式将这个类引入即可。不能使用static的属性类上别忘了加Component让spring管理起来ConfigurationPropertiesConfigurationProperties 注解用于将配置文件中的属性绑定到Java对象中。这使得配置管理更加简洁和方便。特别存在多个属性时比上面value使用更加简单Data ConfigurationProperties(prefix test.msg) public class Test { private String msg;Component注解Component用于标记一个类为组件所以会被SpringBootApplication注解扫描。它可以像普通Bean一样利用Autowired和Value注入泛指各种组件就是说当我们的类不属于各种归类的时候不属于Controller、Services等的时候我们就可以使用Component来标注这个类。import org.springframework.stereotype.Component; Component public class SmsSender {PathVariableDeleteMapping(/delete/{id}) public Object delete(PathVariable Integer id) { return null; }Valid 注解在 RequestBody 前添加验证可以使用以下几种方式使用 Bean Validation 注解在 DTO 类的字段上添加验证注解如 NotNull、NotBlank、Min 等。添加 Valid 注解进行自动验证public WebResponse edit(Valid RequestBody BillAccountInfoDTO dto) {RequestParam注解RequestParam接收的参数是来自HTTP请求体或请求url的QueryString中。RequestParam可以接受简单类型的属性也可以接受对象类型。RequestParam有三个配置参数required 表示是否必须默认为 true必须。defaultValue 可设置请求参数的默认值。value 为接收url的参数名相当于key值。在参数不存在的情况下可能希望变量有一个默认值functionName(RequestParam(valueid[],requiredfalse) ListString id,...注参数名称必须与value里面的完全一样包括那个[]。如果前台用的框架传数组没有那个[]则可以取消掉[]改成idimport org.apache.catalina.connector.Connector; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * springboot解决tomcat拦截GET请求中特殊字符 * * author Administrator */ Configuration public class TomcatConfig { Bean public TomcatServletWebServerFactory webServerFactory() { TomcatServletWebServerFactory factory new TomcatServletWebServerFactory(); factory.addConnectorCustomizers((Connector connector) - { connector.setProperty(relaxedPathChars, \[\\]^{|}); connector.setProperty(relaxedQueryChars, \[\\]^{|}); }); return factory; } }RequestParam用来处理 Content-Type 为application/x-www-form-urlencoded编码的内容Content-Type默认为该属性。RequestParam也可用于其它类型的请求例如POST、DELETE等请求。RequestBody注解注解RequestBody接收的参数是来自requestBody中即请求体。一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据比如application/json、application/xml等类型的数据。就application/json类型的数据而言使用注解RequestBody可以将body里面所有的json数据传到后端后端再进行解析。GET请求中因为没有HttpEntity所以RequestBody并不适用。POST请求中通过HttpEntity传递的参数必须要在请求头中声明数据的类型Content-TypeSpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据然后绑定到相应的bean上。Slf4j注解然后使用log打印日志import lombok.extern.slf4j.Slf4j; Slf4j class LogTest { Test void testLog() { String testInfo Free flying flowers are like dreams; log.info(The test info is :{}, testInfo); } }Autowire注解完成属性装配Autowired private NumberService numberService; public void save() { numberService.findNumber(number); }Autowired装配的是beanimport org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; Configuration //Configuration 相当于 spring中的 application.xml public class ConfigBean { }Pattern注解验证表达式用于String类型Pattern(message 白名单限制规则只能为[enable|disable], regexp ^(enable|disable)$) private String white;NotNullNotBlankNotEmpty三个注解NotEmpty 用在集合类上面加了NotEmpty的String类、Collection、Map、数组是不能为null或者长度为0的(String Collection Map的isEmpty()方法)NotBlank只用于String类型上,不能为null且trim()之后size0。NotNull:不能为null但可以为empty,没有Size的约束。用其做Integer类型字段的校验。而且被其标注的字段可以使用size、Max、Min对字段数值进行大小的控制NotNull(message 每页条数不能为空) Min(value 10, message 每页条数最小为10) private Integer pageSize;Autowired、Inject、Resource三者区别在我们开发spring相关的应用系统时使用Autowired、Resource作为Bean的注入是比较常见的。Inject这个注解我是比较晚毕竟比Resource 对应的规范出来的晚JSR330JSR250嘻嘻才使用到的。1Autowired是spring自带的注解Resource是JSR250规范实现的Inject是JSR330规范实现的需要导入不同的包2Resource如果既没有指定name又没有指定type则自动按照byName方式进行装配如果没有匹配则回退为一个原始类型进行匹配如果匹配则自动装配3Autowired、Inject用法基本一样不同的是Autowired有一个request属性4Autowired如果需要按照名称匹配需要和Qualifier一起使用Inject和Name一起使用5Autowired、Inject是默认按照类型匹配的Resource是按照名称匹配的。

更多文章