@order 指定初始化加载顺序,注入接口的List集合,按顺序排列初始化的bean

Spring 2.0后,Spring提供@Order注解来定义了组件的加载顺序

一、加载顺序源码

public interface Ordered {
    int HIGHEST_PRECEDENCE = -2147483648;
    int LOWEST_PRECEDENCE = 2147483647;

    int getOrder();
}

 

二、测试

包结构:

 

OrderTest接口
public interface OrderTest {
}

实现类

@Order(0)
@Service
public class OrderTest0 implements OrderTest {

    private int order = 0;

    public OrderTest0() {
        System.out.println("order = " + order);
    }
}

.

@Order(5)
@Service
public class OrderTest5 implements OrderTest {

    private int order = 5;

    public OrderTest5() {
        System.out.println("order = " + order);
    }
}

.

@Order(-1)
@Service
public class OrderTest_1 implements OrderTest {

    private int order = -1;

    public OrderTest_1() {
        System.out.println("order = " + order);
    }
}

 .

@Order(-7)
@Service
public class OrderTest_7 implements OrderTest {

    private int order = -7;

    public OrderTest_7() {
        System.out.println("order = " + order);
    }
}

 

测试类

import cc.ash.mvc.service.order.OrderTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class InitOrderTest {

    /**
     * Qualifier 注解,指定注入哪一个实现类
     */
    @Autowired
    @Qualifier("orderTest0")
    private OrderTest orderTest;

    /**
     * 接口集合的方式注入。元素顺序为order指定的加载顺序
     */
    @Autowired
    private List<OrderTest> orderTests;

    @Test
    public void initOrderTest() {
        OrderTest orderTest = orderTests.get(1);
        System.out.println("orderTest = " + orderTest);
    }
}

 .

控制台输出

.

 

...

posted @ 2020-09-09 11:52  毁乐乖狂,自有诪张  阅读(2734)  评论(0编辑  收藏  举报