NOTE

2.55 Spring中如何让A和B两个bean按顺序加载

1. 使用@DependsOn注解 - TestController - TestService - 启动的时候输出 2. 参考 - Spring 中如何控制2个bean中的初始化顺序? \- 知乎 - @DependsOn或depends\-on配置的使用 \- 掘金

Java创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 使用@DependsOn注解

  • TestController
@DependsOn("testService")
@Service
public class TestController
{
    @Autowired
    private TestService testService;
    public TestController()
    {
        System.out.println(this.getClass().getSimpleName() + "初始化。。。");
    }

    public void test()
    {
        String byId = testService.getById(1);
        System.out.println(byId);
    }
}
  • TestService
@Service
public class TestService
{

    public TestService()
    {
        System.out.println(this.getClass().getSimpleName() + "初始化。。。");
    }

    public String getById(Integer id)
    {
        return "" + id;
    }
}
  • 启动的时候输出
TestService初始化。。。
TestController初始化。。。

2. 参考