Spring基础篇(8)-Spring构造函数注入—实现子类的动态注入

需求:根据请求传入的类型,动态的选择不同的子类Bean进行业务处理。

构造函数注入:注入的是Spring容器的Bean对象,使用List作为参数时,是注入某个接口的所有子类对象。

@RestController
public class ConstructorController {

    //注入所有的
    private Map<Integer, AService> mapping = new HashMap<>();

    //将AService接口的子类都注入进来,进行映射处理
    @Autowired
    public ConstructorController(List<AService> serviceList) {
        for (AService aService : serviceList) {
            List<Integer> types = aService.getType();
            for (Integer type : types) {
                mapping.put(type, aService);
            }
        }
    }

    /**
     * 根据type动态获取bean
     *
     * @param type
     * @return
     */
    public AService getBean(Integer type) {
        return mapping.get(type);
    }
    @RequestMapping("/say")
    public String say(@RequestParam int type) {
        return getBean(type).say();
    }
}

接口必须声明一个方法,用于表示子类Bean参与一种或一组类型处理。

/**
 * @author by yexuerui@xdf.cn
 * @Date 2020-10-09 17:05
 */
public interface AService {
    /**
     * 业务方法
     */
    String say();

    /**
     * 每个类均要实现的方法,该子类对应的类型(可能为一组)
     *
     */
    List<Integer> getType();
}

子类的实现类:

@Service
public class A1ServiceImpl implements AService {
    @Override
    public String say() {
        return "A1";
    }

    @Override
    public List<Integer> getType() {
        return Lists.newArrayList(1);
    }
}

请求路径:http://localhost:8083/say?type=1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。