好用的注解

DateTimeFormat

 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date date;
在接受json对象时,在对应的字段上加上这个注解,可以字段转化为日期对象

JsonFormat

@JsonFormat(
            pattern = "yyyy-MM-dd HH:mm:ss"
    )
  在返回json对象,在日期字段上加上这个注解,自动将日期转化成对应格式的字符串

JsonInclude

@JsonInclude(JsonInclude.Include.NON_NULL)
过滤点返回值为null的字段

JsonProperty

@JsonProperty("items")
List<Objecr> userList;
指定返回字段的名称

JsonIgnoreProperties

@JsonIgnoreProperties(ignoreUnknown = true)
这个注解加在类上,当接受的对象,不包含源对象所有的字段时,加上这个注解,不会报错

Profile

@Profile(value = "dev")
该注解加在类上,区分不同的文件执行不同实现方法
@Profile("!test")

**ObjectMapper **

ObjectMapper objectMapper = new ObjectMapper();
    public static <T> T convert2Object(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    public static String convert2String(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }


**ApplicationEventPublisher *

    @Autowired
    private ApplicationEventPublisher publisher;
    public interface ApplicationEventPublisher {

    /**
     * Notify all <strong>matching</strong> listeners registered with this
     * application of an application event. Events may be framework events
     * (such as RequestHandledEvent) or application-specific events.
     * @param event the event to publish
     * @see org.springframework.web.context.support.RequestHandledEvent
 
     */
    void publishEvent(ApplicationEvent event);

    /**
     * Notify all <strong>matching</strong> listeners registered with this
     * application of an event.
     * <p>If the specified {@code event} is not an {@link ApplicationEvent},
     * it is wrapped in a {@link PayloadApplicationEvent}.
     * @param event the event to publish
     * @since 4.2
     * @see PayloadApplicationEvent
     */
    void publishEvent(Object event);

}
 publisher.publishEvent(User.builder().build());
 @EventListener
    public void saveViolationHistory(User user) {
        userRepository.saveUser (
            User .builder()
           .build()
        );
    }

监听事件用法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值