乾貨分享:小技巧大用處之Bean管理類工廠多種實現方式

前言:最近幾個月很忙,都沒有時間寫文章了,今天周末剛好忙完下班相對早點(20:00下班)就在家把之前想總結的知識點寫出來,於是就有了這篇文章。雖無很高深的技術,但小技巧有大用處。

有時我們經常需要將實現了某個基類或某個介面的所有Bean進行分類管理,在需要用到的時候按需獲取實現了某個基類或某個介面的Bean實例對象,那麼我們就需要Bean管理類工廠(即:工廠模式),實現Bean管理類工廠我總結了目前已知且常用的實現方式,敬請各位看官欣賞,如是不足或更好建議歡迎評論區留言指正,謝謝!

為了便於演示,我先自定義如下介面:

/**
 * @author zuowenjun
 *  <pre>www.zuowenjun.cn</pre>
 */
public interface IDemo {
    String getValue();
    int doFor();
}

然後定義3個實現了上述介面的Service Bean類:(注意到Bean類上方還有@DemoFactoryNeedBean這個先不用管,後面的方式中會有用到)

@Service
public class DemoService1 implements IDemo {

    @Override
    public String getValue() {
        return "DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com";
    }

    @Override
    public int doFor() {
        return 1;
    }
}

@DemoFactoryNeedBean
@Service
public class DemoService2 implements IDemo {

    @Override
    public String getValue() {
        return "DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com";
    }

    @Override
    public int doFor() {
        return 2;
    }
}

@DemoFactoryNeedBean
@Service
public class DemoService3 implements IDemo {

    @Override
    public String getValue() {
        return "DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com";
    }

    @Override
    public int doFor() {
        return 3;
    }
}

下面直接無廢話列舉各種實現方式

  1. 實現方式一:直接使用集合的依賴注入方式(利用spring注入時會判斷是否為集合,若為集合則獲取所有實現了該類的BEAN集合併進行注入)

    /**
     * @author zuowenjun
     *  <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory1 {
    
        @Autowired
        private List<IDemo> demos;
    
        public IDemo getOne(int index){
            return demos.stream().filter(d->d.doFor()==index).findFirst().orElseThrow(()->new IllegalArgumentException("not found demo bean"));
        }
    }
    

    單元測試【DemoFactory1】BEAN管理工廠用法及結果:

        @Autowired
        private DemoFactory1 demoFactory1;
        
            @Test
        public void testDemoFactory1(){
            for (int i=1;i<=3;i++){
                    IDemo demo = demoFactory1.getOne(i);
                    System.out.printf("testDemoFactory1--bean class: %s , getValue:%s,  doFor:%d %n", demo.getClass().getSimpleName(), demo.getValue(), demo.doFor());
            }
        }
    

    運行結果:

    testDemoFactory1–bean class: DemoService1 , getValue:DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:1
    testDemoFactory1–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory1–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

  2. 實現方式二:通過實現BeanPostProcessor介面,利用每個BEAN實例化後均會調用postProcessAfterInitialization方法的特點,直接在postProcessAfterInitialization方法中收集所需的BEAN實例並添加到集合中

    /**
     * @author zuowenjun
     *  <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory2 implements BeanPostProcessor {
    
        private List<IDemo> demos=new ArrayList<>();
    
        public IDemo getOne(int index){
            return demos.stream().filter(d->d.doFor()==index).findFirst().orElseThrow(()->new IllegalArgumentException("not found demo bean"));
        }
    
        @Override
        @Nullable
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof IDemo) {
                System.out.printf("postProcessAfterInitialization->bean class:%s",bean.getClass().getSimpleName());
                demos.add((IDemo) bean);
            }
            return bean;
        }
    }
    

    單元測試【DemoFactory2】BEAN管理工廠用法及結果:

        @Autowired
        private DemoFactory2 demoFactory2;
        
            @Test
        public void testDemoFactory2(){
            for (int i=1;i<=3;i++){
                IDemo demo= demoFactory2.getOne(i);
                System.out.printf("testDemoFactory2--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
            }
        }
    

    運行結果:

    testDemoFactory2–bean class: DemoService1 , getValue:DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:1
    testDemoFactory2–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory2–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

  3. 實現方式三:通過實現ApplicationRunner、ApplicationContextAware介面,以便在setApplicationContext能獲取到上下文實例對象並保存,然後在spring初始化完成執行run方法中使用上下文實例對象獲取指定類型的BEAN實例集合。當然也可以不用實現ApplicationRunner介面,而是在工廠方法獲取BEAN對象第一次時才用上下文實例對象獲取指定類型的BEAN實例集合(即:初始化一次)如程式碼中的getOneForLazy方法所示。

    /**
     * @author zuowenjun
     *  <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory3 implements ApplicationRunner, ApplicationContextAware {
    
        private ApplicationContext context;
    
        @Autowired
        private List<IDemo> demos;
    
        public IDemo getOne(int index) {
            return demos.stream().filter(d -> d.doFor() == index).findFirst().orElseThrow(() -> new IllegalArgumentException("not found demo bean"));
        }
    
        public IDemo getOneForLazy(int index) {
            if (CollectionUtils.isEmpty(demos)){
                demos = new ArrayList<>(context.getBeansOfType(IDemo.class).values());
            }
            return demos.stream().filter(d -> d.doFor() == index).findFirst().orElseThrow(() -> new IllegalArgumentException("not found demo bean"));
        }
    
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            demos = new ArrayList<>(context.getBeansOfType(IDemo.class).values());
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context = applicationContext;
        }
    }
    

    單元測試【DemoFactory3】BEAN管理工廠用法及結果:

        @Autowired
        private DemoFactory3 demoFactory3;
    
        @Test
        public void testDemoFactory3(){
            for (int i=1;i<=3;i++){
                IDemo demo= demoFactory3.getOne(i);
                System.out.printf("testDemoFactory3--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
            }
        }
    

    運行結果:

    testDemoFactory3–bean class: DemoService1 , getValue:DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:1
    testDemoFactory3–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory3–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

  4. 實現方式四:此為組合模式,先定義注入ApplicationContext上下文對象,然後定義一個枚舉類,在枚舉類中為每個枚舉項都指明BEAN的實現類型,最後需要獲取BEAN實例時,直接根據上下文對象獲取指定類型的BEAN實例即可。

    
    /**
     * @author zuowenjun
     * <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory4 {
    
        private final ApplicationContext context;
    
        public DemoFactory4(ApplicationContext context) {
            this.context = context;
        }
    
        public IDemo getOne(DemoFactory4Enum factory4Enum) {
            return context.getBean(factory4Enum.getBeanClass());
        }
    
    
        public enum DemoFactory4Enum {
            Demo1(1, DemoService1.class),
            Demo2(2, DemoService2.class),
            Demo3(3, DemoService3.class),
            ;
    
            private final Class<? extends IDemo> beanClass;
            private final int index;
    
            DemoFactory4Enum(int i, Class<? extends IDemo> beanClass) {
                this.index = i;
                this.beanClass = beanClass;
            }
    
            public Class<? extends IDemo> getBeanClass() {
                return beanClass;
            }
    
            public int getIndex() {
                return index;
            }
    
            public static DemoFactory4Enum parse(int i){
                return Arrays.stream(values()).filter(d->d.getIndex()==i).findFirst().orElseThrow(()->new IllegalArgumentException("not found enum item!"));
            }
    
        }
    }
    

    單元測試【DemoFactory4】BEAN管理工廠用法及結果:(演示了2種方式,當然本質都是先確定枚舉項,再獲取BEAN對象)

        @Autowired
        private DemoFactory4 demoFactory4;
        
            @Test
        public void testDemoFactory4(){
    //        for (DemoFactory4.DemoFactory4Enum enumItem:DemoFactory4.DemoFactory4Enum.values()){
    //            IDemo demo= demoFactory4.getOne(enumItem);
    //            System.out.printf("testDemoFactory4--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
    //        }
    
            for (int i=1;i<=3;i++){
                IDemo demo= demoFactory4.getOne(DemoFactory4.DemoFactory4Enum.parse(i));
                System.out.printf("testDemoFactory4--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
            }
        }
    

    運行結果:

    testDemoFactory4–bean class: DemoService1 , getValue:DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:1
    testDemoFactory4–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory4–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

  5. 實現方式五:此為組合模式,與實現方式四有點類似,但又有不同,仍然是先定義注入ApplicationContext上下文對象,然後定義一個抽象枚舉類(有一個抽象方法,如:getBean),在枚舉類中為每個枚舉項都實現這個抽象方法,在抽象方法中通過靜態上下文對象欄位來獲取指定類型的BEAN實例,最後需要獲取BEAN實例就比較簡單了,只要得到枚舉項,就可以直接獲取到對應的BEAN實例。

    
    /**
     * @author zuowenjun
     *  <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory5 {
    
        private static ApplicationContext context;
    
        public DemoFactory5(ApplicationContext context) {
            DemoFactory5.context = context;
        }
    
        public enum DemosEnum {
            Demo1(1) {
                @Override
                public IDemo getBean() {
                    return context.getBean(DemoService1.class);
                }
            },
            Demo2(2) {
                @Override
                public IDemo getBean() {
                    return context.getBean(DemoService2.class);
                }
            },
            Demo3(3) {
                @Override
                public IDemo getBean() {
                    return context.getBean(DemoService3.class);
                }
            },
            ;
    
            private final int index;
    
            DemosEnum(int index) {
                this.index = index;
            }
    
            public int getIndex() {
                return index;
            }
    
            public abstract IDemo getBean();
    
    
            public static DemosEnum parse(int i){
                return Arrays.stream(values()).filter(d->d.getIndex()==i).findFirst().orElseThrow(()->new IllegalArgumentException("not found enum item!"));
            }
    
        }
    }
    

    單元測試【DemoFactory5】BEAN管理工廠用法及結果:(演示了2種方式,當然本質都是先確定枚舉項,再獲取BEAN對象)

        @Test
        public void testDemoFactory5(){
    //        for (DemoFactory5.DemosEnum demosEnum:DemoFactory5.DemosEnum.values()){
    //            IDemo demo= demosEnum.getBean();
    //            System.out.printf("testDemoFactory5--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
    //        }
    
            for (int i=1;i<=3;i++){
                IDemo demo= DemoFactory5.DemosEnum.parse(i).getBean();
                System.out.printf("testDemoFactory5--bean class: %s , getValue:%s,  doFor:%d %n",demo.getClass().getSimpleName(),demo.getValue(),demo.doFor());
            }
        }
    

    運行結果:

    testDemoFactory5–bean class: DemoService1 , getValue:DemoService1.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:1
    testDemoFactory5–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory5–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

  6. 實現方式六:其實本質還是實現方式一的靈活應用,通過自定義標註了@Qualifier註解的過濾註解類(如:@DemoFactoryNeedBean),然後在對應的BEAN類上加上該自定義的過濾註解,最後在工廠類的內部集合依賴注入欄位上同樣增加自定義的過濾註解,這樣就可以在原有的基礎上(BEAN的基類或介面)增加過濾必需包含指明了自定義過濾註解的BEAN實例集合。

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Qualifier
    public @interface DemoFactoryNeedBean {
    }
    
    /**
     * @author zuowenjun
     *  <pre>www.zuowenjun.cn</pre>
     */
    @Service
    public class DemoFactory1 {
    
        @DemoFactoryNeedBean
        @Autowired
        private List<IDemo> demos;
    
        public IDemo getOne(int index){
            return demos.stream().filter(d->d.doFor()==index).findFirst().orElseThrow(()->new IllegalArgumentException("not found demo bean"));
        }
    
        public boolean hasBean(int index){
            return demos.stream().anyMatch(d->d.doFor()==index);
        }
    }
    

    然後再看文章開頭定義的3個BEAN類,其中:DemoService2、DemoService3是有加@DemoFactoryNeedBean註解的,最後再次單元測試【DemoFactory1】BEAN管理工廠用法及結果:

        @Test
        public void testDemoFactory1(){
            for (int i=1;i<=3;i++){
                if (demoFactory1.hasBean(i)) {
                    IDemo demo = demoFactory1.getOne(i);
                    System.out.printf("testDemoFactory1--bean class: %s , getValue:%s,  doFor:%d %n", demo.getClass().getSimpleName(), demo.getValue(), demo.doFor());
                }
            }
        }
    

    運行結果:(少了DemoService1 的BEAN)

    testDemoFactory1–bean class: DemoService2 , getValue:DemoService2.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:2
    testDemoFactory1–bean class: DemoService3 , getValue:DemoService3.getValue by 夢在旅途 zuowj.cnblogs.com, doFor:3

    好了, 以上就是全部的實現方式了,至於哪種更好,我認為在不同的場景下選擇合適的實現方式即可,沒有所謂的最好,存在即有意義,最後期待我下次再寫新的博文吧!~

Tags: