【问题标题】:Spring @Component creation orderSpring @Component 创建顺序
【发布时间】:2020-07-25 19:59:08
【问题描述】:

我试图找到上述问题的答案,但我没有。 那么,什么是 Spring @Component 创建顺序? 例如:我们有

@Component
public class Foo extends SecondClass {
   private SomeType someField;

   @Autowired
   public Foo(SomeType someField){
    super(someField);
   }
}

public class SecondClass implement ISomething {
  //code and @override methods...
  @PostConstruct 
  public void method(ISomething i) {
    //Actions with i
  }
}

创建顺序是什么?在这种特殊情况下,将首先创建什么,父母或孩子?谢谢..

【问题讨论】:

  • 在这种情况下,您只为类 Foo 创建了一个 Bean,它有一个超类 SecondClass

标签: java spring components


【解决方案1】:

为简单起见,忽略将作为 Spring 应用程序的一部分在后台创建的 bean。

由于您在类 Foo 上只有 @Component,因此将创建单个 Spring bean。创建顺序无关紧要,因为这里只创建一个 bean,因为您在任何其他类上都没有 @Component。如果你想使用它,你必须自己手动实例化SecondClass

关于继承问题,Spring 不参与其中。它将由 Java 自己处理。

编辑:

@PostConstruct 将被忽略,因为SecondClass 不是 Spring bean。但是由于我们使用的是super,所以会调用这是一个完整的测试bean创建顺序的程序。

import javax.annotation.PostConstruct;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class TestProgram implements CommandLineRunner {

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

    @Component
    public static class Foo extends SecondClass {
        @Override
        public void method() {
            System.out.println("Printing Foo class");
            //new change
            super.method(); 
        }
    }

    public static class SecondClass implements Cloneable {
        //Since you are calling this method via super in Foo class, you don't need 
        //this annotation as it is being ignored anyway since this class is not a 
        //bean.
        @PostConstruct
        public void method() {
          System.out.println("Printing Second Class");
        }
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Spring application is up.");
    }
}

当我们使用超级调用调用SecondClass 方法时,它现在将打印两者。

打印 Foo 类

印刷二等

SecondClass 中不需要 @PostConstruct,因为它不是 Spring bean,这就是为什么在没有 super 调用的情况下它会被忽略。

通过删除/添加注释来玩,你会得到它。

【讨论】:

  • 谢谢,明白了。我几乎没有编辑我的问题。那么如果我只有 Foo bean,为什么要执行 @PostConstruct 方法?
  • 谢谢,明白了。我们必须添加@Component,让它工作
  • 好吧,我失败了,我已经编辑了我的问题。带有 super() 的构造函数是否完成了 @PostConstruct 方法?
【解决方案2】:

@Order注解定义了注解的组件或bean的排序顺序。它有一个可选的值参数来决定组件的顺序。所以,你可以根据它的优先级来排列你的bean。

【讨论】:

  • 谢谢,这是有用的信息,但我已经有上面显示的工作代码,所以我只想了解它是如何工作的。
  • 如果类 Foo 扩展了 SecondClass 所以,这意味着你必须在 Foo.so 之前初始化 class-bean SecondClass,通过使用 @DependsOn(class name) 你可以在 Foo 类之前初始化 SecondClass
猜你喜欢
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 2019-04-03
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
相关资源
最近更新 更多