Spring bean加载顺序和执行顺序

2 篇文章 0 订阅
在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越优先执行;
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值