美文网首页
springboot实用方法和注解

springboot实用方法和注解

作者: thinking2019 | 来源:发表于2020-06-23 13:50 被阅读0次

1.bean加载之后执行,并只执行一次:

javax.annotation.PostConstruct

2.启动加载数据 接口

org.springframework.boot.CommandLineRunner
org.springframework.boot.ApplicationRunner

3.在指定bean加载之后执行

@AutoConfigureAfter

4.在指定bean加载之前执行

@AutoConfigureBefore

5.条件加载:Conditional
@ConditionalOnProperty

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    String[] value() default {}; //数组,获取对应property名称的值,与name不可同时使用  
  
    String prefix() default "";//property名称的前缀,可有可无  
  
    String[] name() default {};//数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用  
  
    String havingValue() default "";//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置  
  
    boolean matchIfMissing() default false;//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错  
  
    boolean relaxedNames() default true;//是否可以松散匹配,至今不知道怎么使用的  
} 
}

@ConditionalOnBean

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
    /**
     * 需要作为条件的类的Class对象数组
     */
    Class<?>[] value() default {};
    /**
     * 需要作为条件的类的Name,Class.getName()
     */
    String[] type() default {};
    /**
     *  (用指定注解修饰的bean)条件所需的注解类
     */
    Class<? extends Annotation>[] annotation() default {};
    /**
     * spring容器中bean的名字
     */
    String[] name() default {};
    /**
     * 搜索容器层级,当前容器,父容器
     */
    SearchStrategy search() default SearchStrategy.ALL;
    /**
     * 可能在其泛型参数中包含指定bean类型的其他类
     */
    Class<?>[] parameterizedContainer() default {};
}
@ConditionalOnBean**(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)

6.@SneakyThrows 简化trycatch模式,将异常强制转化成RuntimeException,简化如下:

转化前:
    public void method(int i) {
        try{
            int j = 1/i;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

简化后:
    @SneakyThrows
    public void method(int i) {
        int j = 1/i;
    }

相关文章

网友评论

      本文标题:springboot实用方法和注解

      本文链接:https://www.haomeiwen.com/subject/iyfhfktx.html