Spring Boot AutoConfiguration Order

后端 未结 1 1784
滥情空心
滥情空心 2020-12-31 10:08

I am having some trouble getting some Spring configuration to be applied in the desired order with Spring Boot in a multi-module Maven project.

I have modules A and

相关标签:
1条回答
  • 2020-12-31 10:33

    Spring AutoConfiguration is used to provide a basic configuration if certain classes are in the classpath or not.

    This is used e.g. to provide a basic Jpa configuration if Hibernate is on the classpath.

    If you want to configure the order in which beans are instantiated by spring you can use

    @DependsOn("A") 
    public class B{
    ...    
    }
    

    This would create bean "A", than "B".

    However, the order you desire may not be possible. You wrote :

    A depends on C, B depends on A

    If 'depends on' means : A needs C to be instantiated, the beans must be created in the following order :

    1. C - because C depends on nothing
    2. A - because A depends on C, which is already created.
    3. B - because B depends on A, which is already created.

    Spring automatically detects the dependencies by analyzing the bean classes.

    If A has an autowired property or a constructor argument of type C, spring 'knows' that it must instantiate C before A.

    In most cases this works quite well.

    In some cases spring cannot 'guess' the dependencies and creates beans in an unwanted order. Than you can 'inform' spring through the @DependsOn annotation about the dependency. Spring will try to change the order accordingly.

    In your case, if the dependencies you described are not visible for spring, and the dependencies are not needed to create the beans, you can try to change the order with @DependsOn :

    A depends on C, B depends on A

    Could be achieved with

    @DependsOn("C") 
    public class A{
       ...    
    }
    
    @DependsOn("A") 
    public class B{
       ...    
    }
    
    // C comes from another module
    // and no need to annotate
    
    0 讨论(0)
提交回复
热议问题