Spring普通类获取@Service标记的方法或者bean对象

Spring普通类获取@Service标记的方法或者bean对象

今天一个小伙伴问我,在一个listener里面注入serices没法获取到实例,是因为他没有被spring容器加载注入

所以,想要services对象,不能使用@Resouces 来注入了,后来采用了applicationcontext来操作获取到,废话不多少,直接上代码

1、新增一个类:


package com.daolong.sharebook.util;

/**
* @author dengjihai
* @create 2017-11-15
**/

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
* @author dengjh
* @create 2017-11-15
**/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}

public static Object getBean(Class c) {
return applicationContext.getBean(c);
}
}

2、调用获取services:


ApplicationContext appCtx = SpringContextUtil.getApplicationContext();
SdStoreInfoService service = appCtx.getBean(SdStoreInfoService.class);


3、perfect!

  • 发表于 2017-11-15 15:11
  • 阅读 ( 2248 )
  • 分类:Java

0 条评论

请先 登录 后评论
不写代码的码农
伪摄影

22 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章