简介
日常开发中或某些场景时,我们无法声明一个Spring管理的类或我们需要去动态获取Spring管理的类,以便调用该类的内部方法。此时可通过下面几种方法获取。
工具类方式获取
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
直接方式获取
@Service
public class SupperInvoiceFactory {
// 一级部署
@Value("${deploy.model.isFirst}")
public Boolean isFirst = Boolean.TRUE;
@Value("${deploy.model.go.verify.model}")
public Boolean isAisino = Boolean.TRUE;
@Autowired
private ApplicationContext applicationContext;
public SupperInvoiceService build() {
// 一级部署
if (BooleanUtils.isTrue(isFirst)) {
// 平台模式
if (BooleanUtils.isTrue(isKxl)) {
return applicationContext.getBean(FKxlSupperInvoiceServiceImpl.class);
} else {
return applicationContext.getBean(FSgccSupperInvoiceServiceImpl.class);
}
} else {
// 二级平台模式
if(BooleanUtils.isTrue(isKxl)){
return applicationContext.getBean(SKxlSupperInvoiceServiceImpl.class);
} else{
return applicationContext.getBean(SSgccSupperInvoiceServiceImpl.class);
}
}
}
}
结束语
动态获取到Spring管理类后,随意任你处置了😀
网友评论