熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Java中如何獲取Spring中配置的bean

2022-06-13   來源: Java開源技術 

  一什麼是Spring?

  Spring是一個輕量級的控制反轉(IoC)和面向切面(AOP)的容器框架

  二如何在程序中獲取Spring配置的bean呢?

  方法一在初始化時保存ApplicationContext對象

  代碼





ApplicationContext ac = new FileSystemXmlApplicationContex(applicationContextxml);
   acgetBean(beanId);

  ApplicationContext ac = new FileSystemXmlApplicationContex(applicationContextxml);

  acgetBean(beanId);說明這種方式適用於采用Spring框架的獨立應用程序需要程序通過配置文件手工初始化Spring的情況

  方法二通過Spring提供的工具類獲取ApplicationContext對象

  代碼 


















import orgsprntextsupportWebApplicationContextUtils;
    ApplicationContext ac = WebApplicationContextUtils
                               getRequiredWebApplicationContext(ServletContext sc)
    ApplicationContext ac = WebApplicationContextUtils
                               getWebApplicationContext(ServletContext sc)
    acgetBean(beanId);
    acgetBean(beanId);
 
import orgsprntextsupportWebApplicationContextUtils;
    ApplicationContext ac = WebApplicationContextUtils
                               getRequiredWebApplicationContext(ServletContext sc)
    ApplicationContext ac = WebApplicationContextUtils
                               getWebApplicationContext(ServletContext sc)
    acgetBean(beanId);
    acgetBean(beanId);

  方法三繼承自抽象類ApplicationObjectSupport

  說明抽象類ApplicationObjectSupport提供getApplicationContext()方法可以方便的獲取到ApplicationContextSpring初始化時會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入

  方法四繼承自抽象類WebApplicationObjectSupport

  說明類似方法三調用getWebApplicationContext()獲取WebApplicationContext

  方法五實現接口ApplicationContextAware

  說明實現該接口的setApplicationContext(ApplicationContext context)方法並保存ApplicationContext 對象Spring初始化時會通過該方法將ApplicationContext 對象注入


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28587.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.