標籤:err 檔案中 www tar cat get title imp 使用方法
通過ApplicationContextAware載入Spring上下文環境原創 2013年09月05日 18:15:44
- 標籤:
- Spring /
- ApplicationContextAw
項目用到了ApplicationContextAware,通過它Spring容器會自動把上下文環境對象調用ApplicationContextAware介面中的setApplicationContext方法。
我們在ApplicationContextAware的實作類別中,就可以通過這個上下文環境對象得到Spring容器中的Bean。
使用方法如下:
1.實現ApplicationContextAware介面:
[java] view plain copy
- package com.bis.majian.practice.module.spring.util;
-
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
-
- public class SpringContextHelper implements ApplicationContextAware {
- private static ApplicationContext context = null;
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- context = applicationContext;
- }
-
- public static Object getBean(String name){
- return context.getBean(name);
- }
-
- }
2.在Spring的設定檔中配置這個類,Spring容器會在載入完Spring容器後把內容物件調用這個對象中的setApplicationContext方法:
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">
-
- <bean id="springContextHelper" class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>
-
- <context:component-scan base-package="com.bis.majian.practice.module.*" />
- </beans>
3.在web項目中的web.xml中配置載入Spring容器的Listener:
[html] view plain copy
- <!-- 初始化Spring容器,讓Spring容器隨Web應用的啟動而自動啟動 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
4.在項目中即可通過這個SpringContextHelper調用getBean()方法得到Spring容器中的對象了。
通過ApplicationContextAware載入Spring上下文環境