利用Spring的applicationContext实现接口的策略模式

178 阅读1分钟
/**
 * @author xyf
 * @date 2021/7/8 13:29
 */
public interface BaseInterface {

 void method1();

 void method2();


}

/**
     * 枚举类可以方便以后的维护
 */
public enum beanNames {

/**
 *
 */
IMP_TEST1("1", "test1"),
IMP_TEST2("2","test2");


private String name;
private String method;


beanNames(String name, String method) {
	this.name = name;
	this.method = method;
}

public String getName() {
	return this.name;
}

public String getMethod() {
	return this.method;
}

/**
 * 找到枚举类中符合的数据, 如果没有符合的数据,则给他默认的, 具体写法 需要看业务
 * @param name - 枚举类的name属性
 * @return method
 */
public static String getMethod(String name){
	for(beanNames value :beanNames.values()){
		if (value.getName().equals(name)){
			return value.getMethod();
		}
	}
	return IMP_TEST1.getMethod();
}

}


/*
 * 这边自己设置了名称 , 是为了方便, 如果不设置 则为 默认的类名称的首字母小写
 */
@Component("test1")
public class impTest1 implements BaseInterface{
@Override
public void method1() {

	System.out.println("test001---method1");
}

@Override
public void method2() {
	System.out.println("test001---method2");
}


}

@Component("test2")
public class impTest2 implements BaseInterface{
@Override
public void method1() {
	System.out.println("test002---method1");
}

@Override
public void method2() {
	System.out.println("test002---method2");
}


}

// 注意 这个类要想拿到 applicationContext 需要注入 否则再 获取applicationContext 的时候会报 空指针异常
@Component
// 需要 实现 ApplicationContextAware 这样才能拿到 容器的 applicaitonContext
public class strategyFactort implements ApplicationContextAware {

private ApplicationContext applicationContext;

public <T> T getAgent(Class<T> clazz, String beanName) {

	//把所有继承clzz 接口的 类全部取出来 ,返回符合的类即可
	Map<String, T> maps = applicationContext.getBeansOfType(clazz);
	return maps.get(beanName);
}


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.applicationContext = applicationContext;
}
}

public class test {

public static void main(String[] args) {
	// 扫描给定包[spring_test_strategy]中的组件,为这些组件注册 bean 定义,并自动刷新上下文。
	ApplicationContext applicationContext = new AnnotationConfigApplicationContext("spring_test_strategy");
	testController testController = applicationContext.getBean(spring_test_strategy.testController.class);
	testController.test("1");
}
}

@Controller
public class testController {
private final strategyFactort strategyFactort;

public testController(spring_test_strategy.strategyFactort strategyFactort) {
	this.strategyFactort = strategyFactort;
}


public void test(String name){
	BaseInterface baseInterface = strategyFactort.getAgent(BaseInterface.class,beanNames.getMethod(name));
	System.out.println(baseInterface);
	baseInterface.method1();
	baseInterface.method2();

}


}