使用SpringtUtil获取Spring IoC容器中的Bean

<script language=JavaScript src="http://www.pcjx.com/ad/200711/8.js" type=text/javascript> </script>  

功能:
   
方便获取Spring IoC容器中的Bean,调用方法:getBean(String name)

     import org.springframework.context.ApplicationContext;

    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import org.springframework.context.support.FileSystemXmlApplicationContext;

    public class SpringtUtil {

      private static SpringtUtil instance = new SpringtUtil();

      private static ApplicationContext context;

      public static final String spring_context_configfile = "spring.context.configfile";

      public static Object getBean(String name) {

          return getContext().getBean(name);

      }

      public static ApplicationContext getContext() {

            return SpringtUtil.getInstance().context;

     }

        public  static SpringtUtil getInstance()

        {

            return instance;

        }

        private SpringtUtil()

        {

          try

            {

                 String springContextFileName =PropertiesUtil.getProperty(spring_context_configfile);

                 //System.out.println(springContextFileName);

                 context = new FileSystemXmlApplicationContext(springContextFileName);

            } catch (Throwable t) {

                t.printStackTrace();

            }

        }

      public static void main(String[] args)

      {

         try {

             UserService userService= (UserService)SpringtUtil.getBean("userService");

            userService.test("id", "name");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值