1. 程式人生 > >Spring控制Bean初始化順序2

Spring控制Bean初始化順序2

@Order

  • Spring 4.2 利用@Order控制配置類的載入順序

4.2 演示

  • 兩個演示bean
package com.wisely.spring4_2.order;

public class Demo1Service {

}

package com.wisely.spring4_2.order;

public class Demo2Service {

}

  • 兩個配置類,注意@Order配置載入的順序
package com.wisely.spring4_2.order;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(2)
public class Demo1Config {
    @Bean
    public Demo1Service demo1Service(){
        System.out.println("demo1config 載入了");
        return new Demo1Service();
    }

}
package com.wisely.spring4_2.order;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(1)
public class Demo2Config {

    @Bean
    public Demo2Service demo2Service(){
        System.out.println("demo2config 載入了");
        return new Demo2Service();
    }

}
  • 執行
package com.wisely.spring4_2.order;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext("com.wisely.spring4_2.order");
    }


}

輸出結果

demo2config 載入了
demo1config 載入了