zoukankan      html  css  js  c++  java
  • Spring:在普通Java类中获取由Spring所管理的Bean

      一般情况下,在使用SPRING注解的方式管理bean时,只能通过注解或者配置文件注入的方式获取相应的bean。

      但是在某些特殊情况下,我们需要在一个普通的JAVA类中获取由spring所管理的bean,下面是解决办法之一:

      

    第一步:创建一个类并让其实现org.springframework.context.ApplicationContextAware接口,使Spring在启动时注入ApplicationContext对象:

    package com.hsoft.mss.common.utils;
      
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
      
    public class MyApplicationContextUtil implements ApplicationContextAware { 
          
      private static ApplicationContext context;
         
      public void setApplicationContext(ApplicationContext contex) throws BeansException { 
            MyApplicationContextUtil.context=contex; 
      }

      public static ApplicationContext getContext(){
        return context;   } }

    第二步:在spring配置文件中注册上述bean,令服务器启动时加载并将contex对象注入其中:

    <bean class="com.hsoft.mss.common.utils.MyApplicationContextUtil"></bean> 

    第三步:通过上述方法获取重写的contex对象,并通过spring所管理的bean名称得到相应的对象,之后即可使用对象中的各种方法:

    //获取LcfwDao 对象
    LcfwDao lcfwDao = (LcfwDao) MyApplicationContextUtil.getContext().getBean("lcfwDaoImpl"); 
    //调用其中的方法
    int count = lcfwDao.getCountById("18");
  • 相关阅读:
    操作系统
    C++流类库(11)
    C++运算符重载(10)
    C++虚函数(09)
    C++向量(08)
    C++继承(07)
    ResNet实战
    ResNet,DenseNet
    经典卷积网络VGG,GoodLeNet,Inception
    CIFAR100与VGG13实战
  • 原文地址:https://www.cnblogs.com/mmlw/p/3754025.html
Copyright © 2011-2022 走看看