成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

Spring獲取管理對象常用方法詳解

瀏覽:7日期:2023-08-07 08:50:50

網上方法很多種,我說一些J2EE開發中會用到的方法。

第一種:

直接初始化Spring容器,獲得對象

ApplicationContext applicationContext = new ClassPathXmlApplicationContext('applicationContext.xml'); applicationContext.getBean('beanId');

關于配置文件的讀取也有好多種,我用到的是配置文件在SRC下面。

這樣會初始化Spring容器,然后再得到配置的對象。

第二種:

通過環境來獲得

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); ac1.getBean('beanId'); ac2.getBean('beanId');

區別是前者會拋異常,而后者沒有時返回NULL

第三種:

實現ApplicationContextAware接口

下面給出實現類,這也是我用的方法

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @說明 獲得Spring配置中的某個對象 * @author 崔素強 * @see */ public class SpringFactory implements ApplicationContextAware { private static ApplicationContext context; @SuppressWarnings('static-access') @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } public static Object getObject(String id) { Object object = null; object = context.getBean(id); return object; } }

這是WEB開發中可以用到的集中方法,當然還有其他方法,歡迎大家積極提供!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章: