java静态方法中获取spring容器中的bean
获取上下文工具类:package com.hikvision.pvia.kafka.utils;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationCont
·
获取上下文工具类:
package com.hikvision.pvia.kafka.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取上下文信息
*
* @author suyl
* @version v1.0
* @update 2020-05-11 10:19
**/
@Component
public class ApplicationContextProviderUtils implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProviderUtils.applicationContext = applicationContext;
}
/**
* 获取Spring上下文
*
* @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 <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
静态方法中用法:
public class KafkaFactory {
/* 获取上下文 */
static ApplicationContextProviderUtils applicationContextProvider = new ApplicationContextProviderUtils();
/* 日志 */
static Logger logger = LoggerFactory.getLogger(KafkaFactory.class);
public static void sendToKafka(String data) {
KafkaProducer producer = (KafkaProducer)
applicationContextProvider.getBean("kafkaProducer");
producer.send(data);
// 此处省略
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)