Spring中@DependsOn注解的作用

133 阅读1分钟

介绍

该注解用于显示的指定Bean之间的依赖关系,而不是通过Spring的依赖解析机制自行判断。被@DependOn注解指定的Bean会先于当前Bean产生。

Demo

测试实体类

    public static class DependsOnEntityA {
        public DependsOnEntityA() {
            System.out.println("DependsOnEntityA init");
        }
    }

    public static class DependsOnEntityB {
        public DependsOnEntityB() {
            System.out.println("DependsOnEntityB init");
        }
    }

未指定@DependsOn注解测试

配置类

	@Configuration
    public static class NonDependsOnConf {
        @Bean
        public DependsOnEntityA getDependOnEntityA() {
            return new DependsOnEntityA();
        }

        @Bean
        public DependsOnEntityB getDependOnEntityB() {
            return new DependsOnEntityB();
        }
    }

测试

	@Test
    public void nonDependOnTest() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(NonDependsOnConf.class);
        applicationContext.refresh();
    }

结果

DependsOnEntityA init
DependsOnEntityB init

Spring默认会按自然排序创建Bean

指定了@DependsOn注解测试

配置类

 	@Configuration
    public static class DependsOnConf {
        @DependsOn("getDependOnEntityB")
        @Bean
        public DependsOnEntityA getDependOnEntityA() {
            return new DependsOnEntityA();
        }

        @Bean
        public DependsOnEntityB getDependOnEntityB() {
            return new DependsOnEntityB();
        }
    }

测试

	@Test
    public void dependOnTest() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(DependsOnConf.class);
        applicationContext.refresh();
    }

结果

DependsOnEntityB init
DependsOnEntityA init