Spring学習ノート(七)

2833 ワード

1、ビーンはSpring容器をどうやって取得しますか?
1)、     ,       web.xml            Spring  ,    Bean     Spring     ,          
2)、   :  BeanFactoryAware  ,           ,void setBeanFactory(BeanFactory beanFactory),           Bean BeanFactory。  Bean       ,Spring                    。
3)、        :  ApplicationContextAware  ,          ,void setApplicationContext(ApplicationContext applicationContext)。
2、Application Contect Awareインターフェースを実現したクラスを作成する:
package com.sxit.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

//   ApplicationContextAware  ,                 Spring  
public class Chinese implements ApplicationContextAware {

	private ApplicationContext apc;
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.apc = applicationContext;
	}

	public ApplicationContext getApc() {
		return apc;
	}
}
3、xml設定ファイル:
<?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-3.0.xsd ">

	<bean id="chinese" class="com.sxit.service.Chinese" />
		
</beans>
4、テストクラス:
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sxit.service.Chinese;

public class Test2 {

	public static void main(String[] args) {

		ApplicationContext apc = new ClassPathXmlApplicationContext("Bean3.xml");
		Chinese chinese = apc.getBean("chinese", Chinese.class);
		System.out.println("chinese    :"+chinese.getApc());
		System.out.println("  :"+apc);
		System.out.println(chinese.getApc()==apc);
	}
}
 5、印刷情報:
chinese    :org.springframework.context.support.ClassPathXmlApplicationContext@c1b531: startup date [Tue Nov 06 08:41:52 GMT 2012]; root of context hierarchy
  :org.springframework.context.support.ClassPathXmlApplicationContext@c1b531: startup date [Tue Nov 06 08:41:52 GMT 2012]; root of context hierarchy
true
 6、まとめ:
1)、   ApplicationContextAware   Bean              ,       Spring       ,         。