本文分类:
Spring

问题的背景是一个接口有多个实现,想通过一个工厂类的静态方法选择不同的实现,代码如下,关键点在于 Bean 的容器注入和 PostConstruct。

package com.hiwzc.spring.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class DemoServiceFactory {

    private static DemoServiceFactory instance;

    @Autowired
    private List<DemoService> serviceList;

    @Autowired
    private Map<String, DemoService> serviceMap;

    public static void show() {
        System.out.println("size = " + instance.serviceList.size());
        System.out.println("map = " + instance.serviceMap);
    }

    @PostConstruct
    private void init() {
        DemoServiceFactory.instance = this;
    }
}
本文来自 [时光记 - 王智超的个人空间](www.hiwzc.com),转载请注明出处。