Spring框架注解说明

2020-10-02  本文已影响0人  我菠菜今天就是要为所欲为

WEB类

@CrossOrigin

@RequestParam(value = "$count", required = false)

@RequestBody

获取Post请求中的请求体。

@PathVariable

组件类

@PostConstruct

@PreDestory

@Component

泛指组件,当组件不好归类的时候,使用Component进行标注

@Controller

控制层标记,用于标注控制层组件,基于@Component

@Service

业务层标记,用于标注业务层组件,基于@Component

@Repository

持久层标记,用于标注数据库访问组件,基于@Component

@Autowired

接口可以被容器注入

@Qualifier

当接口有多个实现类的时候,使用这个注解声明使用哪个实现

@ComponentScan({“com.x.x.x”,”com.x.y.y})

指定Spring扫描包的范围,SpringBoot默认扫描SpringApplication类下的所有包,如果不在其包下,则可以使用这个注解扫描指定的包,扩大spring的扫描范围

@Retryable

引用

<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>

开启retry

@SpringBootApplication
@EnableRetry
public class DatasyncApplication {

    public static void main(String[] args)  {
        SpringApplication.run(DatasyncApplication.class, args);
    }
}

在指定方法上标记@Retryable来开启重试

@Retryable(value={A异常.class,B异常.class},
maxAttempts=重试次数,
backoff = @Backoff(value = 每次重试延迟毫秒数))
public Integer retry() {
    LOGGER.info(“测试retry”);
    final int a = 5;
    int num = new SecureRandom().nextInt();
    if (num % a == 0) {
        return num;
    }
    throw new RetryException(“重试失败”);
}

在指定方法上标记@Recover来开启重试失败后调用的方法(注意,需跟重处理方法在同一个类中)

@Recover
public void recover(A异常 e) {
// … do something
}

@Recover
public void recover(B异常 e) {
// … do something
}

@Backoff注解

delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调

上一篇 下一篇

猜你喜欢

热点阅读