1.前言
我有一个需求:有四个系统需要处理字段,一开始利用switch-case进行区分编码,后期字段处理越来越多,导致switch-case代码冗余,不太好,然后想通过java单继承多实现的性质进行优化。
2.实现
2.1定义Spring boot 上下文环境
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@SuppressWarnings("static-access")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param
* @return
*/
public static
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param
* @return
*/
public static
return getApplicationContext().getBean(name, clazz);
}
}
2.2创建接口
public interface UserService {
//获取用户的主要任务
String getTask();
}
2.3多实现
@Service("student")
public class StudentServiceImpl implements UserService {
@Override
public String getTask() {
return "学生在学习";
}
}
@Service("admin")
public class TeacherServiceImpl implements UserService {
@Override
public String getTask() {
return "管理员在管理";
}
}
2.4引入上下文,通过接口调用方法
@Resource
private ApplicationContext applicationContext;
UserService userService = applicationContext.getBean("student", UserService );
String task = userService.getTask();