在spring中,有时会存在实现多个相同类/接口的bean,而有时我们希望bean的加载或执行按照某种顺序执行。
二话不说,先给出一个实现控制bean加载和执行顺序的实例

有一个测试接口TestInterface,及其三个实现类:UnitTest、InterTest、UiTest,希望按照UiTest->InterTest->UnitTest的顺序加载bean,并按照UnitTest->InterTest->UiTest顺序执行
  • 定义一个测试接口
package com.example.beans;
public interface TestInterface {

    void run();
}

  • 定义枚举变量,按bean期望的执行顺序定义变量
package com.example.beans;
public enum TestEnum {

    InterTest,
    unitTest;
}

  • 实现三个测试类实例,并实现Ordered接口,来控制执行顺序
package com.example.beans;

import org.springframework.core.Ordered;

public class UnitTest implements TestInterface, Ordered {

    public UnitTest() {
        System.out.println("init unitTest");
    }

    @Override
    public void run() {
        System.out.println("run unitTest");
    }

    @Override
    public int getOrder() {
        return TestEnum.unitTest.ordinal();
    }
}

  • 定义configure类定义bean
package com.example.beans;

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

@Configuration
public class BeanConfig {

    @Bean
    public TestInterface uiTest() {
        return new UiTest();
    }

    @Bean
    public TestInterface interTest() {
        return new InterTest();
    }

    @Bean
    public TestInterface unitTest() {
        return new UnitTest();
    }
}

  • 注入bean并执行
package com.example;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.beans.TestInterface;

@RestController("/")
@ComponentScan(value = {"com.example"})
@EnableAutoConfiguration
public class Example {

    @Autowired(required = false)
    List<TestInterface> tests;

    @RequestMapping("/home")
    String home() {

        if (!ObjectUtils.isEmpty(tests)) {
            for (TestInterface test : tests) {
                test.run();
            }
        }

        return "hello world";
    }

    public static void main(String[] args) throws Exception {

        SpringApplication.run(Example.class, args);
    }
}

以上实例,

  1. 通过@Configuration注解类中bean的定义顺序控制bean的加载顺序;
  2. 通过bean实现Ordered接口的getOrder方法来控制bean的执行顺序,getOrder越小,bean越优先执行;
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐