Java动态获取实现类 Class.forName(clazz).newInstance()和applicationContext.getBean, bean Map寻找方式,Java Map定义和初始化方法

Java动态获取实现类 Class.forName(clazz).newInstance()和applicationContext.getBean, bean Map寻找方式,Java Map定义和初始化方法

1.定义枚举类MyServiceTypeEnum.java

package com.example.core.mydemo.bean;

public enum MyServiceTypeEnum {
    SUBMIT_ORDER_SUCCESS("submitOrder", "com.example.core.mydemo.bean.MySubmitOrderImplOneService"),//下单
    CANCEL_ORDER_SUCCESS("cancelOrder", "com.example.core.mydemo.bean.MyCancelOrderImplOneService"),//取消

    //java.lang.ClassNotFoundException: MySubmitOrderImplOneService  类的路径需要完整的路径。
//    SUBMIT_ORDER_SUCCESS("submitOrder", "MySubmitOrderImplOneService"),//下单
//    CANCEL_ORDER_SUCCESS("cancelOrder", "MyCancelOrderImplOneService"),//取消
    ;
    private String name;
    private String value;

    MyServiceTypeEnum(String name, String value) {
        this.value = value;
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public String getName() {
        return name;
    }

    /**
     * 获取服务模版
     * @param name
     * @return
     */
    public static String getServiceTemplate(String name) {
        for (MyServiceTypeEnum messageServiceTypeEnum : values()) {
            if (messageServiceTypeEnum.getName().equals(name)) {
                return messageServiceTypeEnum.getValue();
            }
        }
        return null;
    }

}

2.定义接口类  MyOrderImplOneService.java

package com.example.core.mydemo.bean;

public interface MyOrderImplOneService {
    /**
     * 获取类名称
     * @return
     */
    public String getClassName();
}

3.定义提交订单实现类 MySubmitOrderImplOneService.java

package com.example.core.mydemo.bean;

public class MySubmitOrderImplOneService implements MyOrderImplOneService{
    @Override
    public String getClassName() {
        return "hello " + MySubmitOrderImplOneService.class.getName();
    }
}

4.定义取消订单实现类 MyCancelOrderImplOneService.java

package com.example.core.mydemo.bean;

public class MyCancelOrderImplOneService implements MyOrderImplOneService{

    @Override
    public String getClassName() {
        return "hello " + MyCancelOrderImplOneService.class.getName();
    }
}

5.测试类

package com.example.core.mydemo.bean;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.beans.ImmutableBean;
import org.springframework.context.ApplicationContext;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * output:
 * myOrderImplOneService class name=hello com.example.core.mydemo.bean.MySubmitOrderImplOneService
 * myOrderImplOneService class name=hello com.example.core.mydemo.bean.MyCancelOrderImplOneService
 * myOrderImplOneService5 class name=hello com.example.core.mydemo.bean.MySubmitOrderImplOneService
 * myOrderImplOneService6 class name=hello com.example.core.mydemo.bean.MyCancelOrderImplOneService
 *
 */
public class MyServiceTest {

    @Resource
    private ApplicationContext applicationContext;

    //模拟  java8新特性-双括号初始化
/*    public Map<String,Class> beanMap = new HashMap<String,Class>(){{
        put("submitOrder",MySubmitOrderImplOneService.class);
        put("cancelOrder",MyCancelOrderImplOneService.class);
    }};*/

    //java9新特性
//    public Map<String,Class> beanMap = Map.of("","","","");

    //Guava
//    public Map<String,Class> beanMap = ImmutableMap.of("","","","");


    //静态块的方式初始化
    public static final Map<String,Class> beanMap = new HashMap<String,Class>();
    static {
        beanMap.put("submitOrder",MySubmitOrderImplOneService.class);
        beanMap.put("cancelOrder",MyCancelOrderImplOneService.class);
    }

    /**
     * bean寻找方法
     * @param name
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private MyOrderImplOneService beanRouting(String name) throws IllegalAccessException, InstantiationException {
        return (MyOrderImplOneService) beanMap.get(name).newInstance();

//        if (name.equals(MyServiceTypeEnum.SUBMIT_ORDER_SUCCESS.getName())) {
//            return (MyOrderImplOneService) beanMap.get(name).newInstance();
//        }else if(name.equals(MyServiceTypeEnum.CANCEL_ORDER_SUCCESS.getName())){
//            return (MyOrderImplOneService) beanMap.get(name).newInstance();
//        }
//        return null;  //默认
    }

    /**
     * Class.forName(clazz).newInstance()
     * @param name
     * @return
     */
    public static MyOrderImplOneService getInstance(String name) {
        MyOrderImplOneService inter = null;
        String clazz = MyServiceTypeEnum.getServiceTemplate(name);
        if (name != null && StringUtils.isNotEmpty(clazz)) {
            try {
                inter = (MyOrderImplOneService) Class.forName(clazz).newInstance();//调用无参构造器创建实例
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return inter;
    }

    /**
     * applicationContext.getBean方式
     * @param name
     * @return
     */
    private  MyOrderImplOneService routing(String name) {
        if (name.equals(MyServiceTypeEnum.SUBMIT_ORDER_SUCCESS.getName())) {
            return applicationContext.getBean(MySubmitOrderImplOneService.class);
        }else if(name.equals(MyServiceTypeEnum.CANCEL_ORDER_SUCCESS.getName())){
            return applicationContext.getBean(MyCancelOrderImplOneService.class);
        }
        return null;  //默认
    }

    public static void main(String[] args) {
        /**
         * Class.forName(clazz).newInstance()
         */
        //java.lang.ClassNotFoundException: MySubmitOrderImplOneService
        MyOrderImplOneService myOrderImplOneService = MyServiceTest.getInstance("submitOrder");
        System.out.println("myOrderImplOneService class name=" + myOrderImplOneService.getClassName());

        MyOrderImplOneService myOrderImplOneService2 = MyServiceTest.getInstance("cancelOrder");
        System.out.println("myOrderImplOneService class name=" + myOrderImplOneService2.getClassName());

        /**
         * applicationContext.getBean方式
         * applicationContext加载方式,需要在容器中。
         */
//        MyOrderImplOneService myOrderImplOneService3 = new MyServiceTest().routing("submitOrder");
//        System.out.println("myOrderImplOneService3 class name=" + myOrderImplOneService3.getClassName());
//
//        MyOrderImplOneService myOrderImplOneService4 = new MyServiceTest().routing("cancelOrder");
//        System.out.println("myOrderImplOneService4 class name=" + myOrderImplOneService4.getClassName());

        /**
         * bean寻找方法
         */
        try {
            MyOrderImplOneService myOrderImplOneService5 = new MyServiceTest().beanRouting("submitOrder");
            System.out.println("myOrderImplOneService5 class name=" + myOrderImplOneService5.getClassName());

            MyOrderImplOneService myOrderImplOneService6 = new MyServiceTest().beanRouting("cancelOrder");
            System.out.println("myOrderImplOneService6 class name=" + myOrderImplOneService6.getClassName());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

posted on 2024-06-06 19:44  oktokeep  阅读(13)  评论(0编辑  收藏  举报