1. 程式人生 > >Spring 自定義Bean 實例獲取

Spring 自定義Bean 實例獲取

pan 定義 turn get 漏洞 封裝 @override stat public

一、通過指定配置文件獲取, 對於Web程序而言,我們啟動spring容器是通過在web.xml文件中配置,這樣相當於加載了兩次spring容器

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId"); 

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

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
ApplicationContext ac2 
= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); MyService service1 = (MyService)ac1.getBean("bean1");//這是beanId. MyService service2 = (MyService)ac2.getBean("bean2");

  這種方式明顯有很大的漏洞,其一:需要request對象,其二:很難封裝一個Java工具類

三、實現接口ApplicationContextAware, 或繼承實現ApplicationContextAware接口的類

package com.zxguan;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;

/**
 * @author zxguan
 * @description
 * @create 2018-01-29 14:54
 */
public class SpringTool extends ApplicationObjectSupport {

    
private static ApplicationContext applicationContext = null; @Override protected void initApplicationContext(ApplicationContext context) throws BeansException { super.initApplicationContext(context); if (null == SpringTool.applicationContext) { SpringTool.applicationContext = context; } } public static ApplicationContext getAppContext() { return applicationContext; } public static Object getBean(String beanId){ return getAppContext().getBean(beanId); } }

  還需將類 SpringTool 交由 Spring容器管理

Spring 自定義Bean 實例獲取