根據(jù)不同的條件,調(diào)用不同的 bean 對(duì)象,執(zhí)行對(duì)象中的方法
Spring的Factories 配置方式 容器注入
SpringUtils 工具類
package com.vipsoft.web.utils;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring工具類 方便在非 Spring 管理環(huán)境中獲取bean
*
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {
/**
* Spring 應(yīng)用上下文環(huán)境
*/
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
/**
* 獲取對(duì)象
*
* @param name
* @return Object 一個(gè)以所給名字注冊(cè)的bean的實(shí)例
* @throws BeansException
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 獲取類型為requiredType的對(duì)象
*
* @param clz
* @return
* @throws BeansException
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一個(gè)與所給名稱匹配的bean定義,則返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 判斷以給定名字注冊(cè)的bean定義是一個(gè)singleton還是一個(gè)prototype。 如果與給定名字相應(yīng)的bean定義沒有被找到,將會(huì)拋出一個(gè)異常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注冊(cè)對(duì)象的類型
* @throws NoSuchBeanDefinitionException
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
/**
* 如果給定的bean名字在bean定義中有別名,則返回這些別名
*
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
/**
* 獲取aop代理對(duì)象
*
* @param invoker
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker) {
return (T) AopContext.currentProxy();
}
/**
* 獲取當(dāng)前的環(huán)境配置,無配置返回null
*
* @return 當(dāng)前的環(huán)境配置
*/
public static String[] getActiveProfiles() {
return applicationContext.getEnvironment().getActiveProfiles();
}
/**
* 獲取當(dāng)前的環(huán)境配置,當(dāng)有多個(gè)環(huán)境配置時(shí),只獲取第一個(gè)
*
* @return 當(dāng)前的環(huán)境配置
*/
public static String getActiveProfile() {
final String[] activeProfiles = getActiveProfiles();
return ArrayUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
}
執(zhí)行類文章來源:http://www.zghlxwxcb.cn/news/detail-413078.html
package com.vipsoft.web.task;
import cn.hutool.core.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component("scheduletask")
public class ScheduleTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
public void execute(String param) {
logger.info("執(zhí)行 Schedule Task,當(dāng)前時(shí)間:{},任務(wù)參數(shù):{}", DateUtil.now(), param);
}
}
測(cè)試類文章來源地址http://www.zghlxwxcb.cn/news/detail-413078.html
package com.vipsoft.web;
import cn.hutool.core.util.StrUtil;
import com.vipsoft.web.utils.SpringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.lang.reflect.Method;
@SpringBootTest
public class SpringUtilTest {
@Test
void invokeTest() throws Exception {
//點(diǎn)前面的做為 bean 名稱,后面是方法名,(中是參數(shù)==參數(shù)可以放JSON)
String invokeTarget = "scheduletask.execute('VipSoft Quartz')";
invokeMethod(invokeTarget);
}
void invokeMethod(String invokeTarget) throws Exception {
String beanName = StrUtil.subBefore(invokeTarget, ".", true);
String methodName = StrUtil.subBetween(invokeTarget, ".", "(");
String param = StrUtil.subBetween(invokeTarget, "(", ")");
Object bean;
if (StrUtil.count(beanName, ".") == 0) {
bean = SpringUtils.getBean(beanName);
} else {
//Package 的形式得到 Bean,如: beanName="com.vipsoft.web.task.ScheduleTask"
bean = Class.forName(beanName).newInstance();
}
if (bean != null) {
if (StrUtil.isNotEmpty(param)) {
Method method = bean.getClass().getDeclaredMethod(methodName, String.class);
method.invoke(bean, param);
} else {
Method method = bean.getClass().getDeclaredMethod(methodName);
method.invoke(bean);
}
}
}
}
到了這里,關(guān)于Java SpringBoot 中,動(dòng)態(tài)執(zhí)行 bean 對(duì)象中的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!