spring 动态加载bean(续----前一篇kafka消费者线程池)

1.将初始化放在容器启动之后


/**
* 动态注入消费者线程
*
* @create 2017-11-06 20:14
* @update 2017-11-06 20:14
**/
@Component
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

@Resource
KafkaConsumerPool consumerPool;
@Resource
KafkaConsumerConfig consumerConfig;

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

ConsumerGroup consumerThread2 = new ConsumerGroup("gropu-2","access_data", consumerConfig);

/**
* 各起两个消费者 ,Kafka consumer是非线程安全的 Consumer 需要一个new 的
*/
creatComsumer("gropu-1","access_data",2);
creatComsumer("gropu-2","access_data",2);
}

private void creatComsumer(String groupId, String topic,int count) {
ConsumerGroup consumerThread = new ConsumerGroup(groupId,topic,consumerConfig);
for (int i = 0; i <count ; i++) {
Consumer consumer = SpringBeanFactory.getBean(Consumer.class);
consumer.setConsumer(consumerThread);
consumerPool.SubmitConsumerPool(consumer);
}
}
}

动态获取bean
 1 @Component
 2 public class SpringBeanFactory implements ApplicationContextAware  {
 3 
 4     private static final Log log = LogFactory.getLog(SpringBeanFactory.class);
 5 
 6     private static ApplicationContext applicationContext;
 7 
 8     @Override
 9     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
10         if(SpringBeanFactory.applicationContext == null){
11             SpringBeanFactory.applicationContext  = applicationContext;
12         }
13     }
14 
15     public static <T> T getBean(Class<T> clazz){
16         try {
17             return applicationContext.getBean(clazz);
18         } catch (Exception e) {
19             log.info(e.getMessage());
20         }
21         return null;
22     }
23 
24     /**
25        * 从当前IOC获取bean
26        *
27        * @param id
28        *            bean的id
29        * @return
30       */
31      public static Object getObject(String id) {
32         Object object = null;
33         object = applicationContext.getBean(id);
34         return object;
35      }
36 
37     //通过name,以及Clazz返回指定的Bean
38     public static <T> T getBean(String name,Class<T> clazz){
39         return getApplicationContext().getBean(name, clazz);
40     }
41 
42 
43     public static ApplicationContext getApplicationContext() {
44         return applicationContext;
45     }
46 }

实现效果:

 

posted @ 2017-11-06 20:43  Enast  阅读(536)  评论(0编辑  收藏  举报