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


使用Spring框架,我们不需要创建类的对象,都有Spring 容器创建,并通过注解来注入。注入的原理就是在程序启动的时候,Spring根据xml中配置的路径来扫描类,如果发现类的上方有类似@Service,@Controller,此时就会定位到当前类,然后来给当前类中标有注解的属性进行注入,从而我们可以使用该属性,调用方法。

那么普通类怎么使用@Service标记的方法呢?

1.如果你想用@autowired,那么这个类本身也应该是在spring的管理下 的,即你的UserLogUtil也要标注为一个component(或Service),这样spring才知道要注入依赖;
2. 如果不标注为@Component的话,此时不能通过@autowired来注入依赖,只能通过ApplicationContext来取得标注为Service的类:
UserLogService service = ApplicationContext.getBean(UserLogService.class);


写一个工具类实现ApplicationContextAware接口,并将这个加入到spring的容器(推荐)

public class JsonDataUtil implements ApplicationContextAware {
  /**
   * 实现ApplicationContextAware接口,并将这个加入到spring的容器
   */
  private static ApplicationContext applicationContext = null;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    JsonDataUtil.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);
  }

  然后将此bean注册到spring 的容器中,在spring的配置文件添加如下代码

<bean id="JsonDataUtil" class="com.powerbridge.utils.JsonDataUtil"></bean>

  最后在普通类就可以这样调用

ApplicationContext appCtx = JsonDataUtil.getApplicationContext();
    WorkSpaceService workSpaceService =  (WorkSpaceService)JsonDataUtil.getBean(WorkSpaceService.class);

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM