Springboot实战系列之@Autowired注入类的list

一个回调接口有多种回调逻辑,在项目启动时需要将回调接口的实现类都放到一个list中然后回调每个实现类的具体方法。在Springboot中就可以通过@Autowired来将回调接口的所有实现类进行注入。

Demo

回调接口: ServiceTest

public interface ServiceTest {
    public String getName();
}

实现类1

@Component
public class ServiceTestImpl1 implements ServiceTest {
    @Override
    public String getName() {
        return "ServiceTestImpl1";
    }
}

实现类2

@Component
public class ServiceTestImpl2 implements ServiceTest {
    @Override
    public String getName() {
        return "ServiceTestImpl2";
    }
}

实现类3

@Component
public class ServiceTestImpl3 implements ServiceTest {
    @Override
    public String getName() {
        return "ServiceTestImpl3";
    }
}

测试类

@Component
public class Test implements InitializingBean {

    @Autowired
    private List serviceTests;

    public String serviceTest() {
        StringBuffer sb = new StringBuffer();
        for (ServiceTest serviceTest : serviceTests) {
            sb.append(serviceTest.getName());
            sb.append(" ");
        }
        return sb.toString();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(serviceTest());
    }
}

输出

ServiceTestImpl1 ServiceTestImpl2 ServiceTestImpl3 

你可能感兴趣的:(Springboot实战系列之@Autowired注入类的list)