获取上下文工具类:

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);
        // 此处省略
    }
}

 

Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐