Spring(4) Bean獲取Spring容器
阿新 • • 發佈:2018-12-02
- 當一個bean需要獲取它所在spring容器的時候,實際上這種情況是很常見的,例如要輸出國際化資訊,釋出事件等。
- bean可以通過實現BeanFactoryAware介面實現獲取它所在的spring容器,BeanFactoryAware只有一個setBeanFactory方法,spring容器會檢測容器所有的bean,如果發現有bean實現了BeanFactoryAware(當然這個類已經實現了setBeanFactory方法),它會把它所在的容器當作引數傳給它。
- 下面是一個例子,具體講解穿插在程式碼裡邊。
- 程式結構
-
package service; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.util.Locale; /** * Person類實現了ApplicationContextAware介面,spring會把它所在的容器當作引數給他的setApplicationContext * 方法 */ public class Person implements ApplicationContextAware { private ApplicationContext applicationContext; // 這個變數用來儲存它所在的spring容器 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void sayHi(String name){ System.out.println(applicationContext. getMessage("hello", new String[]{name}, Locale.getDefault(Locale.Category.FORMAT))); // 在獲取了spring容器之後,這個bean就可以使用已經儲存有它所在的spring容器來獲取國際化資原始檔 } }
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.Person; /** * 邏輯是這樣的,程式會先把spring容器給Person類,然後在這裡使用的時候,Person類已經有了 * sprig容器了,其他的就輸出輸出,沒有什麼了 */ public class SpringTest { public static void main(String []args){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml"); Person person = applicationContext.getBean("person", Person.class); person.sayHi("java"); } }
兩個配置檔案和前面的一樣,就不多說了
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--這裡是使用國際化資原始檔,和前面例子的操作是一樣的--> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>message</value> </list> </property> </bean> <!--獲取spring容器的bean在配置上和普通的bean是一樣的--> <bean id="person" class="service.Person"/> </beans>