您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBean如何獲取Spring容器操作,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
具體如下:
一 配置
<?xml version="1.0" encoding="GBK"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 加載容器國際化所需要的語言資源文件 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>message</value> </list> </property> </bean> <!-- Spring容器會檢測容器中所有Bean,如果發(fā)現(xiàn)某個Bean實現(xiàn)了 ApplicationContextAware接口,Spring容器會在創(chuàng)建該Bean之后, 自動調(diào)用該Bean的setApplicationContext()方法,調(diào)用該方法時, 會將容器本身作為參數(shù)傳給該方法。--> <bean id="person" class="org.crazyit.app.service.Person"/></beans>
二 資源文件
hello=\u6b22\u8fce\u4f60\uff0c{0}now=\u73b0\u5728\u65f6\u95f4\u662f\uff1a{0}
三 Bean
package org.crazyit.app.service;import org.springframework.context.*;import org.springframework.beans.BeansException;import java.util.Locale;public class Person implements ApplicationContextAware{ // 將BeanFactory容器以成員變量保存 private ApplicationContext ctx; /* Spring容器會檢測容器中所有Bean,如果發(fā)現(xiàn)某個Bean實現(xiàn)了ApplicationContextAware接口, Spring容器會在創(chuàng)建該Bean之后,自動調(diào)用該方法,調(diào)用該方法時, 會將容器本身作為參數(shù)傳給該方法。*/ public void setApplicationContext(ApplicationContext ctx) throws BeansException { this.ctx = ctx; } public void sayHi(String name) { System.out.println(ctx.getMessage("hello" , new String[]{name} , Locale.getDefault(Locale.Category.FORMAT))); }}
四 測試類
package lee;import java.io.*;import org.springframework.context.*;import org.springframework.context.support.*;import org.crazyit.app.service.*;public class SpringTest{ public static void main(String[] args)throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Person p = ctx.getBean("person" , Person.class); p.sayHi("孫悟空"); }}
以上是“SpringBean如何獲取Spring容器操作”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。