Bean獲取Spring容器

一、目的
在某些特殊情況下,Bean需要實現某個功能,比如該bean需要輸出國際化消息,或者該bean需要向Spring發佈事件,但該功能必須藉助於Spring容器才能實現,此時就必須讓該Bean先獲取Spring容器,然後藉助於Spring容器來實現該功能。
爲了讓Bean獲取它所在的Spring容器,可以讓該Bean實現BeanFactoryAware接口。類似接口如:BeanNameAware,ResourceLoaderAware,ApplicationContextAware接口
二、示例

package com.home.bean;
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Persons implements ApplicationContextAware{
    //將BeanFactory容器以成員變量保存
    private ApplicationContext ctx;
    /*
     * Spring容器會檢測容器中所有bean,如果發現某個bean實現了ApplicationContextAware接口,Spring容器
     * 會在創建該bean之後,自動調用該方法,調用該方法時,會將該容器本身作爲參數傳遞給該方法
     */
    public void setApplicationContext(ApplicationContext ctx)
            throws BeansException {
        // TODO Auto-generated method stub
        this.ctx=ctx;
    }
    public void sayHello(String name){
        System.out.println(ctx.getMessage("hello", new String[]{name},Locale.getDefault()));
    }
}
配置文件如下:
 <!-- 國際化配置開始 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
       <!-- 驅動spring調用messageSource bean的setBasenems()方法,該方法需要一個數組參數,使用list元素配置多個數組元素 -->
       <property name="basenames">
            <list>
                <value>message</value>
            </list>
             <!-- 如果有多個資源文件,全部列在此處 -->
       </property>
    </bean>
    <bean id="persons" class="com.home.bean.Persons"></bean>
 國際化配置信息如下:
 hello=\u6B22\u8FCE\u4F60\uFF0C{0}
 now=\u73B0\u5728\u65F6\u95F4\u662F,{0}

 測試代碼:
 package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.home.bean.Persons;
/**
 *執行Persons對象的方法sayHello()方法時,該方法就自動具有了國際化的功能,
 *而這種國際化功能實際上是由spring容器提供的,
 *這就是讓Bean獲取他的容器的好處
 */
public class BeanGetApplication{
    public static void main(String[] args) throws Exception{
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        Persons p=ctx.getBean("persons", Persons.class);
        p.sayHello("中文讓");
    }
}
發佈了91 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章