IOC概念,反射例子

64 篇文章 0 订阅

http://blog.csdn.net/benjamin_whx/article/details/41791707

Ioc概念:

包括两个内容:控制&反转

对于软件来说,是某一接口具体实现类的选择控制权从调用类中移除,转交给第三方决定。DI(依赖注入:Dependency Injection)即让调用类对某一接口实现类的依赖由第三方(容器或协作类)注入,以移除调用类对某一接口实现类的依赖。


Ioc类型:从注入方法上看,主要可以划分为三种类型:构造函数注入、属性注入和接口注入。


反射在Ioc中的应用,小例子:

Car.class

  1. package com.wiseweb.ioc;  
  2.   
  3. public class Car {  
  4.       
  5.     private String brand ;  
  6.       
  7.     private String color ;  
  8.       
  9.     private int maxSpeed ;  
  10.       
  11.     public Car(){}  
  12.       
  13.     public Car(String brand, String color, int maxSpeed) {  
  14.         this.brand = brand ;  
  15.         this.color = color ;  
  16.         this.maxSpeed = maxSpeed ;  
  17.     }  
  18.       
  19.     public void introduce() {  
  20.         System.out.println("brand:" + brand + ";color:" +color + ";maxSpeed" + maxSpeed);  
  21.     }  
  22.     public String getBrand() {  
  23.         return brand;  
  24.     }  
  25.     public void setBrand(String brand) {  
  26.         this.brand = brand;  
  27.     }  
  28.     public String getColor() {  
  29.         return color;  
  30.     }  
  31.     public void setColor(String color) {  
  32.         this.color = color;  
  33.     }  
  34.     public int getMaxSpeed() {  
  35.         return maxSpeed;  
  36.     }  
  37.     public void setMaxSpeed(int maxSpeed) {  
  38.         this.maxSpeed = maxSpeed;  
  39.     }  
  40.       
  41. }  
ReflectTest.class

  1. package com.wiseweb.ioc;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.Method;  
  5.   
  6. public class ReflectTest {  
  7.     public static Car initByDefaultConst() throws Throwable {  
  8.         ClassLoader loader = Thread.currentThread().getContextClassLoader() ;  
  9.         Class clazz = loader.loadClass("com.wiseweb.ioc.Car") ;  
  10.           
  11.         Constructor cons = clazz.getDeclaredConstructor((Class[])null) ;  
  12.         Car car = (Car)cons.newInstance() ;  
  13.           
  14.         Method setBrand = clazz.getMethod("setBrand", String.class) ;  
  15.         setBrand.invoke(car, "红旗") ;  
  16.         Method setColor = clazz.getMethod("setColor", String.class) ;  
  17.         setColor.invoke(car, "黑色") ;  
  18.         Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class) ;  
  19.         setMaxSpeed.invoke(car, 200) ;  
  20.         return car ;  
  21.     }  
  22.       
  23.     public static void main(String[] args) throws Throwable {  
  24.         Car car = initByDefaultConst() ;  
  25.         car.introduce() ;  
  26.     }  
  27. }  

输出:brand:红旗;color:黑色;maxSpeed200


类装载器ClassLoader的工作机制:类装载器就是寻找类的字节码文件并构造出类在JVM内部表示的对象组件。在Java中,类装载器把一个类装入JVM中,要经过以下步骤:

1、装载:查找和导入class文件;

2、链接:执行校验、准备和解析步骤,其中解析步骤是可以选择的:

a、校验:检查载入class文件数据的正确定;

b、准备:给类的静态变量分配存储空间;

c、解析:将符号引用转成直接引用;

3、初始化:对类的静态变量、静态代码块执行初始化工作。

类装载工作由ClassLoader及其子类负责,ClassLoader是一个重要的Java运行时系统组件,它负责在运行时查找和装入Class字节码文件。JVM在运行时会产生三个ClassLoader:根装载器、ExtClassLoader(扩展类装载器)和AppClassLoder(系统类装载器)。其中,根装载器不是ClassLoader子类,它使用c++编写,因此我们在java中看不到它,根装载器负责装载JRE的核心类库,如JRE目标下的rt.jar、charsets.jar等。ExtClassLoader和AppClassLoader都是ClassLoader的子类。其中ExtClassLoader负责装载JRE扩展目录ext中的JAR类包;AppClassLoader负责装载Classpath路径下的类包。

这三个类装载器之间存在父子层级关系,即根装载器是ExtClassLoader的父装载器,ExtClassLoader是AppClassLoader的父装载器。默认情况下,使用AppClassLoader装载应用程序的类。

  1. package com.wiseweb.ioc;  
  2.   
  3. public class ClassLoaderTest {  
  4.     public static void main(String[] args) {  
  5.         ClassLoader loader = Thread.currentThread().getContextClassLoader() ;  
  6.         System.out.println("current loader:" + loader);  
  7.         System.out.println("parent loader:" + loader.getParent());  
  8.         System.out.println("grandparent loader:" + loader.getParent().getParent());  
  9.     }  
  10. }  


输出:current loader:sun.misc.Launcher$AppClassLoader@70a0afab
  parent loader:sun.misc.Launcher$ExtClassLoader@456d3d51
  grandparent loader:null


JVM装载类时使用“全盘负责委托机制”,“全盘负责”是指当一个ClassLoader装载一个类时,除非显示地使用另一个ClassLoader,该类所依赖及引用的类也由这个ClassLoader载入;“委托机制”是指先委托父装载器寻找目标类,只有在找不到的情况下才从自己的类路径中查找并装载目标类。这一点是从安全角度考虑的,试想如果有人编写了一个恶意的基础类(如java.lang.String)并装载到JVM中将会引起多么可怕的后果。但是由于有了“全盘负责委托机制”,java.lang.String永远是由根装载器来装载的,这样就避免了上述时间的发生。


Spring的Resource接口及其实现类可以在脱离Spring框架的情况下使用,它比通过JDK访问资源的API更好用,更强大。

假设有一个文件位于Web应用的类路径下,用户可以通过以下方式对这个文件资源进行访问:

1、通过FileSystemResource以文件系统绝对路径的方式进行访问;

2、通过ClassPathResource以类路径的方式进行访问;

3、通过ServletContextResource以相对于Web应用根目录的方式进行访问。


  1. package com.wiseweb.ioc;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5.   
  6. import org.springframework.core.io.ClassPathResource;  
  7. import org.springframework.core.io.FileSystemResource;  
  8. import org.springframework.core.io.Resource;  
  9.   
  10.   
  11. public class FileSourceExample {  
  12.     public static void main(String[] args) {  
  13.         try {  
  14.             String filePath = "F:/workspace/httpClient/src/conf/file1.txt" ;  
  15.             Resource res1 = new FileSystemResource(filePath) ;  
  16.             Resource res2 = new ClassPathResource("conf/file1.txt") ;  
  17.               
  18.             InputStream ins1 = res1.getInputStream() ;  
  19.             InputStream ins2 = res2.getInputStream() ;  
  20.             System.out.println("res1: " + res1.getFilename());  
  21.             System.out.println("res2: " + res2.getFilename());  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  
  26. }  

输出:res1: file1.txt
  res2: file1.txt


资源加载时默认采用系统编码读取资源内容,如果资源文件采用特殊的编码格式,那么可以通过EncodedResource对资源进行编码,以保证资源内容操作的正确性。

  1. package com.wiseweb.ioc;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileWriter;  
  5.   
  6. import org.springframework.core.io.ClassPathResource;  
  7. import org.springframework.core.io.Resource;  
  8. import org.springframework.core.io.support.EncodedResource;  
  9. import org.springframework.util.FileCopyUtils;  
  10.   
  11. public class EncodedResourceExample {  
  12.     public static void main(String[] args) throws Throwable {  
  13.         Resource res = new ClassPathResource("conf/file1.txt") ;  
  14.         EncodedResource encRes = new EncodedResource(res, "utf-8") ;  
  15.         String content = FileCopyUtils.copyToString(encRes.getReader()) ;  
  16.         System.out.println(content);  
  17.         File f = new File("d:/a.txt") ;  
  18.         FileWriter fw = new FileWriter(f) ;  
  19.         //Spring的文件copy,传入一个输入流,一个输出流。  
  20.         FileCopyUtils.copy(encRes.getReader(), fw) ;  
  21.     }  
  22. }  

ApplicationContext介绍:

如果配置文件被防止在类路径下,用户可以优先使用ClassPathXmlApplicationContext实现类:

ApplicationContext ctx = new ClassPathXmlApplicationContext("com/baobaotao/context/beans.xml") ;


还可以指定一组配置文件,Spring会自动将多个配置文件在内存中“整合”成一个配置文件,如下所示:

ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"conf/beans1.xml","conf/beans2.xml"}) ;


ApplicationContext的初始化和BeanFactory有一个重大的区别:BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean时才实例目标Bean;而ApplicationContext则在初始化应用上下文时就实例化所有单实例Bean。因此ApplicationContext的初始化时间会比BeanFactory稍长一些,不过稍后的调用则没有“第一次惩罚”的问题。


Spring3.0后支持类注解的配置方式:

  1. package com.baobaotao.entity;  
  2.   
  3. public class Car {  
  4.     private String brand ;  
  5.     private String color ;  
  6.     private int maxSpeed ;  
  7.       
  8.     public Car() {  
  9.         super();  
  10.     }  
  11.     public Car(String brand, String color, int maxSpeed) {  
  12.         super();  
  13.         this.brand = brand;  
  14.         this.color = color;  
  15.         this.maxSpeed = maxSpeed;  
  16.     }  
  17.     public String getBrand() {  
  18.         return brand;  
  19.     }  
  20.     public void setBrand(String brand) {  
  21.         this.brand = brand;  
  22.     }  
  23.     public String getColor() {  
  24.         return color;  
  25.     }  
  26.     public void setColor(String color) {  
  27.         this.color = color;  
  28.     }  
  29.     public int getMaxSpeed() {  
  30.         return maxSpeed;  
  31.     }  
  32.     public void setMaxSpeed(int maxSpeed) {  
  33.         this.maxSpeed = maxSpeed;  
  34.     }  
  35.       
  36.     public void introduce() {  
  37.         System.out.println("brand:" + brand + ";color" + color + ";maxSpeed" + maxSpeed);  
  38.     }  
  39. }  
  1. package com.baobaotao.context;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.Configuration;  
  5.   
  6. import com.baobaotao.entity.Car;  
  7. //表示这是一个配置信息提供类  
  8. @Configuration  
  9. public class Beans {  
  10.     //定义一个Bean  
  11.     @Bean(name="car")  
  12.     public Car buildCar() {  
  13.         Car car = new Car() ;  
  14.         car.setBrand("红旗CA72") ;  
  15.         car.setMaxSpeed(200) ;  
  16.         return car ;  
  17.     }  
  18. }  

  1. package com.baobaotao.context;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  5.   
  6. import com.baobaotao.entity.Car;  
  7.   
  8. public class AnnotationApplicationContext {  
  9.     public static void main(String[] args) {  
  10.         ApplicationContext ctx = new AnnotationConfigApplicationContext(Beans.class) ;  
  11.         Car car = ctx.getBean("car", Car.class) ;  
  12.         System.out.println(car.getBrand());  
  13.     }  
  14. }  


WebApplicationCOntext是专门为Web应用准备的,它允许从相对于Web根目录的路径中装载配置文件完成初始化工作。从WebApplicationContext中可以获得ServletContext的引用,整个Web应用上下文对象将最为属性放置到ServletContext中,以便Web应用环境可以访问Spring应用上下文。

WebApplicationContext定义了一个常量ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,在上下文启动时,WebApplicationContext实例即以此为键放置在ServletContext的属性列表中,因此我们可以直接通过以下语句从web容器中获取WebApplicationContext:

  1. WebApplicationContext wac = (WebApplicationContext)servletContext.  
  2.         getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) ;  


WebApplicationContext的初始化方式和BeanFactory、ApplicationContext有所区别,因为WebApplicationCOntext需要ServletContext实例,也就是说它必须在拥有Web容器的前提下才能完成启动的工作。有过Web开发经验的人都知道在web.xml中配置自启动的Servlet或定义Web容器监听器(ServletContextListener),借助这两者中的任何一个,我们就可以完成启动Spring Web应用上下文的工作。

下面是使用ContextLoaderListener启动WebApplicationContext的具体配置:

  1. <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>  
  4.         /WEB-INF/baobaotao.xml,/WEB-INF/baobaotao-service.xml  
  5.     </param-value>  
  6.   </context-param>  
  7.     
  8.   <listener>  
  9.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  10.   </listener>  

如果使用Web监听器,则必须将Log4jConfigListener防止在ContextLoaderListener的前面。采用下面的配置方式Spring将自动使用XmlWebApplicationContext启动Spring容器,即通过XML文件为Spring容器提供Bean的配置信息。

  1. <context-param>  
  2.         <param-name>log4jConfigLocation</param-name>  
  3.         <param-value>WEB-INF/log4j.properties</param-value>  
  4.     </context-param>  
  5.   
  6.     <context-param>  
  7.         <param-name>log4jRefreshInterval</param-name>  
  8.         <param-value>60000</param-value>  
  9.     </context-param>  
  10.   
  11.     <listener>  
  12.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  13.     </listener>  

如果使用@Configuration的Java类提供配置信息,则web.xml的配置需要按以下方式配置:

  1. <context-param>  
  2.         <param-name>contextClass</param-name>  
  3.         <param-value>  
  4.             org.springframework.web.context.support.AnnotationConfigWebApplicationContext  
  5.         </param-value>  
  6.     </context-param>  
  7.       
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>com.baobaotao.AppConfig1,com.baobaotao.AppConfig2</param-value>  
  11.     </context-param>  
  12.       
  13.     <listener>  
  14.         <listener-class>  
  15.             org.springframework.web.context.ContextLoaderListener  
  16.         </listener-class>  
  17.     </listener>  



Bean的生命周期:

下面用例子说明BeanFactory中Bean的生命周期:

  1. package com.baobaotao.entity;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.beans.factory.BeanFactory;  
  5. import org.springframework.beans.factory.BeanFactoryAware;  
  6. import org.springframework.beans.factory.BeanNameAware;  
  7. import org.springframework.beans.factory.DisposableBean;  
  8. import org.springframework.beans.factory.InitializingBean;  
  9. //管理bean生命周期的接口  
  10. public class Car implements BeanFactoryAware,BeanNameAware,InitializingBean,DisposableBean{  
  11.     private String brand ;  
  12.     private String color ;  
  13.     private int maxSpeed ;  
  14.     private BeanFactory beanFactory ;  
  15.     private String beanName ;  
  16.       
  17.     public Car() {  
  18.         super();  
  19.         System.out.println("调用car构造函数。");  
  20.     }  
  21.     public String getBrand() {  
  22.         return brand;  
  23.     }  
  24.     public void setBrand(String brand) {  
  25.         System.out.println("设置setBrand()设置属性。");  
  26.         this.brand = brand;  
  27.     }  
  28.     public String getColor() {  
  29.         return color;  
  30.     }  
  31.     public void setColor(String color) {  
  32.         this.color = color;  
  33.     }  
  34.     public int getMaxSpeed() {  
  35.         return maxSpeed;  
  36.     }  
  37.     public void setMaxSpeed(int maxSpeed) {  
  38.         this.maxSpeed = maxSpeed;  
  39.     }  
  40.       
  41.     public void introduce() {  
  42.         System.out.println("brand:" + brand + ";color" + color + ";maxSpeed" + maxSpeed);  
  43.     }  
  44.     //BeanFactoryAware接口方法  
  45.     public void setBeanFactory(BeanFactory beanFactory) throws BeansException {  
  46.         System.out.println("调用BeanFactoryAware.setBeanFactory()。");  
  47.         this.beanFactory = beanFactory ;  
  48.     }  
  49.     //BeanNameAware接口方法  
  50.     public void setBeanName(String beanName) {  
  51.         System.out.println("调用BeanNameAware.setBeanName()。");  
  52.         this.beanName = beanName ;  
  53.     }  
  54.     //InitializongBean接口方法  
  55.     public void afterPropertiesSet() throws Exception {  
  56.         System.out.println("调用InitilizingBean.afterPropertiesSet()。");  
  57.     }  
  58.     //DisposableBean接口方法  
  59.     public void destroy() throws Exception {  
  60.         System.out.println("调用DisposableBean.destroy()。");  
  61.     }  
  62.     //通过<bean>的init-method属性指定的初始化方法  
  63.     public void myInit() {  
  64.         System.out.println("调用init-method所指定的myInit(),将maxSpeed设置为240。");  
  65.         this.maxSpeed = 240 ;  
  66.     }  
  67.     //通过<bean>的destroy-method属性指定的销毁方法  
  68.     public void myDestroy() {  
  69.         System.out.println("destroy-method所指定的myDestroy()。");  
  70.     }  
  71. }  

  1. package com.baobaotao.beanfactory;  
  2.   
  3. import java.beans.PropertyDescriptor;  
  4.   
  5. import org.springframework.beans.BeansException;  
  6. import org.springframework.beans.PropertyValues;  
  7. import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;  
  8.   
  9. public class MyInstantiationAwarePostProcessor extends InstantiationAwareBeanPostProcessorAdapter{  
  10.     //接口方法,在实例化后调用  
  11.     @Override  
  12.     public boolean postProcessAfterInstantiation(Object bean, String beanName)  
  13.             throws BeansException {  
  14.         if("car".equals(beanName)) {  
  15.             System.out.println("InstantiationAware BeanPostProcessor.postProcessAfterInstantiation");  
  16.         }  
  17.         return super.postProcessAfterInstantiation(bean, beanName);  
  18.     }  
  19.     //接口方法,在实例化Bean前调用  
  20.     @Override  
  21.     public Object postProcessBeforeInstantiation(Class<?> beanClass,  
  22.             String beanName) throws BeansException {  
  23.         if("car".equals(beanName)) {  
  24.             System.out.println("InstantiationAware BeanPostProcessor.postProcessBeforeInstantiation");  
  25.         }  
  26.         return null;  
  27.     }  
  28.     //接口方法,在设置某个属性时调用  
  29.     @Override  
  30.     public PropertyValues postProcessPropertyValues(PropertyValues pvs,  
  31.             PropertyDescriptor[] pds, Object bean, String beanName)  
  32.             throws BeansException {  
  33.         if("car".equals(beanName)) {  
  34.             System.out.println("InstantiationAware BeanPostProcessor.postProcessPropertyValues");  
  35.         }  
  36.         return pvs;  
  37.     }  
  38.       
  39. }  

  1. package com.baobaotao.beanfactory;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.beans.factory.config.BeanPostProcessor;  
  5.   
  6. import com.baobaotao.entity.Car;  
  7.   
  8. public class MyBeanPostProcessor implements BeanPostProcessor{  
  9.       
  10.     public Object postProcessBeforeInitialization(Object bean, String beanName)  
  11.             throws BeansException {  
  12.         if(beanName.equals("car")) {  
  13.             Car car = (Car)bean ;  
  14.             if(car.getColor() == null) {  
  15.                 System.out.println("调用BeanPostProcessor.postProcessBeforeInitialization()," +  
  16.                         "color为空,设置为默认黑色。");  
  17.                 car.setColor("黑色") ;  
  18.             }  
  19.         }  
  20.         return bean;  
  21.     }  
  22.   
  23.     public Object postProcessAfterInitialization(Object bean, String beanName)  
  24.             throws BeansException {  
  25.         if(beanName.equals("car")) {  
  26.             Car car = (Car)bean ;  
  27.             if(car.getMaxSpeed() >= 200) {  
  28.                 System.out.println("调用BeanPostProcessor.postProcessAfterInitialization()," +  
  29.                         "将maxSpeed调正为200。");  
  30.                 car.setMaxSpeed(200) ;  
  31.             }  
  32.         }  
  33.         return bean;  
  34.     }  
  35.   
  36.       
  37.   
  38.   
  39. }  

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.     http://www.springframework.org/schema/context   
  8.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  9.     <bean id="car" class="com.baobaotao.entity.Car" init-method="myInit"   
  10.         destroy-method="myDestroy" scope="singleton">  
  11.         <property name="brand" value="红旗CA72"></property>  
  12.         <property name="maxSpeed" value="200"></property>  
  13.     </bean>  
  14. </beans>  

  1. package com.baobaotao.beanfactory;  
  2.   
  3. import org.springframework.beans.factory.BeanFactory;  
  4. import org.springframework.beans.factory.config.ConfigurableBeanFactory;  
  5. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  6. import org.springframework.core.io.ClassPathResource;  
  7. import org.springframework.core.io.Resource;  
  8.   
  9. import com.baobaotao.entity.Car;  
  10.   
  11. public class BeanLifeCycle {  
  12.     @SuppressWarnings("deprecation")  
  13.     public static void LifeCycleBeanFactory() {  
  14.         Resource res = new ClassPathResource("com/baobaotao/beanfactory/beans.xml") ;  
  15.         BeanFactory bf = new XmlBeanFactory(res) ;  
  16.         ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyBeanPostProcessor()) ;  
  17.         ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyInstantiationAwarePostProcessor()) ;  
  18.         //第一次从容器中获取car,将出发容器实例化该Bean,这将引发Bean生命周期方法的调用  
  19.         Car car1 = (Car)bf.getBean("car") ;  
  20.         car1.introduce() ;  
  21.         car1.setColor("红色") ;  
  22.           
  23.         //第二次从容器中获取car,直接从缓存池中获取  
  24.         Car car2 = (Car)bf.getBean("car") ;  
  25.         System.out.println("car1==car2:" + (car1==car2));  
  26.         //关闭容器  
  27.         ((XmlBeanFactory)bf).destroySingletons() ;  
  28.     }  
  29.     public static void main(String[] args) {  
  30.         LifeCycleBeanFactory() ;  
  31.     }  
  32. }  

输出:

  1. InstantiationAware BeanPostProcessor.postProcessBeforeInstantiation  
  2. 调用car构造函数。  
  3. InstantiationAware BeanPostProcessor.postProcessAfterInstantiation  
  4. InstantiationAware BeanPostProcessor.postProcessPropertyValues  
  5. 设置setBrand()设置属性。  
  6. 调用BeanNameAware.setBeanName()。  
  7. 调用BeanFactoryAware.setBeanFactory()。  
  8. 调用BeanPostProcessor.postProcessBeforeInitialization(),color为空,设置为默认黑色。  
  9. 调用InitilizingBean.afterPropertiesSet()。  
  10. 调用init-method所指定的myInit(),将maxSpeed设置为240。  
  11. 调用BeanPostProcessor.postProcessAfterInitialization(),将maxSpeed调正为200。  
  12. brand:红旗CA72;color黑色;maxSpeed200  
  13. car1==car2:true  
  14. 调用DisposableBean.destroy()。  
  15. destroy-method所指定的myDestroy()。  

如果配置文件中定义了多个工厂后处理器,最好让它们实现org.springframework.core.Ordered接口,以便Spring以确定的顺序调用它们。

ApplicationContext和BeanFactory一个最大的不同之处在于:前者会利用Java反射机制自动识别出配置文件中定义的BeanPostProcessor、InstantiationAwareBeanPostProcess和BeanFactoryProcessor,并自动将它们注册到应用上下文中;而后者需要在代码中通过手工调用addBeanPostProcessor()方法进行注册。这也是为什么在应用开发时,我们普遍使用ApplicationContext而很少使用BeanFactory的原因之一。





总结:

控制反转:

“控制”是接口实现类的选择控制权

“反转”是指这种选择控制权从调用类转移到外部第三方类或容器的手中


依赖注入参数详解:

  1. <bean id="car" class="com.baobaotao.entity.Car">  
  2.         <property name="maxSpeed">  
  3.             <value>200</value>  
  4.         </property>  
  5.         <property name="brand">  
  6.             <value><![CDATA[红旗&CA72]]></value>  
  7.         </property>  
  8.     </bean>  

上面代码中的brand属性值包含了一个XML的特殊符号,因此我在属性值外加了一个<![CDATA[]]>的XML特殊处理标签,<![CDATA[]]>的作用是让XML解析器将标签中的字符串当作普通的文本对待,以防止某些字符串对XML格式造成破坏。

XML中共有5个特殊的字符,分别是:&<>"',上面所说的是一种解决办法,还有一种是使用XML转义序列表示这些特殊的字符,下面定义了这些特殊字符对应的转义序列:

<       &lt;

>&gt;

&&amp;

"&quot;

'&apos;



Bean的作用域:singleton、prototype、request、session、globalSession

Bean的默认作用域为singleton。

Spring的ApplicationContext容器在启动时,自动实例化所有Singleton的Bean并缓存于容器中。虽然启动时会花费一些时间,但带来两个好处:首先对Bean提前的实例化操作会及早发现一些潜在的配置问题;其次Bean以缓存的方式保存,当运行期使用到该Bean时就无须再实例化了,加快了运行的效率。如果用户不希望在容器启动时提前实例化singleton的Bean,可以通过lazy-init属性进行控制:


<bean id="boss1" class="com.baobaotao.scope.Boss" p:car-ref="car" lazy-init="true" >


@Autowired默认按类型匹配注入Bean,@Resource则按名称匹配注入Bean。@Inject和@Autowired一样也是按类型匹配注入Bean的,只不过它没有required属性。可见不管事@Resource还是@Inject注解,其功能都没有@Autowired丰富,因此除非必要,大可不必在乎这两个注解。


Spring为注解配置提供了一个@Scope的注解,可通过它显示指定Bean的作用范围:

例如:@Scope("prototype")


Spring从2.5开始支持JSR-250中定义的@PostConstruct和@PreDestroy注解,在Spring中它们相当于init-method和destroy-method属性的功能,不过使用注解时,可以在一个Bean中定义多个@PostConstruct和@PreDestroy



自定义属性编辑器:

Spring大部分默认属性编辑器都直接扩展于java.beans.PropertyEditorSupport类,用户也可以通过扩展PropertyEditorSupport实现自己的属性编辑器。比起用于IDE环境的属性编辑器来说,Spring环境下使用的属性编辑器的功能非常单一:仅需要将配置文件中字面值转换为属性类型的对象即可,并不需要提供UI界面,因此仅需要简单覆盖PropertyEditorSupport的setAsText()方法就可以了。


  1. package com.baobaotao.editor;  
  2.   
  3. public class Car {  
  4.     private int maxSpeed ;  
  5.     private String brand ;  
  6.     private double price ;  
  7.     public int getMaxSpeed() {  
  8.         return maxSpeed;  
  9.     }  
  10.     public void setMaxSpeed(int maxSpeed) {  
  11.         System.out.println("maxSpeed注入进来:" + maxSpeed);  
  12.         this.maxSpeed = maxSpeed;  
  13.     }  
  14.     public String getBrand() {  
  15.         return brand;  
  16.     }  
  17.     public void setBrand(String brand) {  
  18.         System.out.println("brand注入进来:" + brand);  
  19.         this.brand = brand;  
  20.     }  
  21.     public double getPrice() {  
  22.         return price;  
  23.     }  
  24.     public void setPrice(double price) {  
  25.         System.out.println("price注入进来:" + price);  
  26.         this.price = price;  
  27.     }  
  28.       
  29.       
  30. }  


  1. package com.baobaotao.editor;  
  2.   
  3. public class Boss {  
  4.     private String name ;  
  5.     private Car car = new Car() ;  
  6.     public String getName() {  
  7.         return name;  
  8.     }  
  9.     public void setName(String name) {  
  10.         this.name = name;  
  11.     }  
  12.     public Car getCar() {  
  13.         return car;  
  14.     }  
  15.     public void setCar(Car car) {  
  16.         this.car = car;  
  17.     }  
  18.       
  19. }  

  1. package com.baobaotao.editor;  
  2.   
  3. import java.beans.PropertyEditorSupport;  
  4.   
  5. public class CustomCarEditor extends PropertyEditorSupport{  
  6.   
  7.     @Override  
  8.     public void setAsText(String text) {  
  9.         if(text == null || text.indexOf(",") == -1) {  
  10.             throw new IllegalArgumentException("设置的字符串格式不正确") ;  
  11.         }  
  12.         String[] infos = text.split(",") ;  
  13.         Car car = new Car() ;  
  14.         car.setBrand(infos[0]) ;  
  15.         car.setMaxSpeed(Integer.parseInt(infos[1])) ;  
  16.         car.setPrice(Double.parseDouble(infos[2])) ;  
  17.         setValue(car) ;  
  18.     }  
  19.       
  20. }  


  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.     http://www.springframework.org/schema/context   
  8.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  9.     <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
  10.         <property name="customEditors">  
  11.             <map>  
  12.                 <entry key="com.baobaotao.editor.Car">  
  13.                     <bean class="com.baobaotao.editor.CustomCarEditor"></bean>  
  14.                 </entry>  
  15.             </map>  
  16.         </property>  
  17.     </bean>  
  18.       
  19.     <bean id="boss" class="com.baobaotao.editor.Boss">  
  20.         <property name="name" value="John" />  
  21.         <property name="car" value="红旗CA72,200,2000.00" />  
  22.     </bean>  
  23. </beans>  

  1. package com.baobaotao.editor;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class CustomTest {  
  7.     public static void main(String[] args) {  
  8.         ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml") ;  
  9.         Boss boss = (Boss)ac.getBean("boss") ;  
  10.         System.out.println(boss.getCar().getBrand());  
  11.     }  
  12. }  


输出:brand注入进来:红旗CA72
maxSpeed注入进来:200
price注入进来:2000.0
红旗CA72


使用外部属性文件:

  1. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"  
  2.         p:location="classpath:com/baobaotao/placeholder/jdbc.properties"  
  3.         p:fileEncoding="utf-8"/>  
  4.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  5.         destroy-method="close"  
  6.         p:driverClassName="${driverClassName}"  
  7.         p:url="${url}"  
  8.         p:username="${username}"  
  9.         p:password="${password}"/>  


PropertyPlaceholderConfigurer其他属性:

1、locations:如果只有一个属性文件,直接使用location属性指定就可以了,如果是多个属性文件,则可以通过locations属性进行设置,可以像配置List一样配置locations属性。

2、fileEncoding:属性文件的编码格式,Spring使用操作系统默认编码读取属性文件,如果属性文件采用了特殊编码,需要通过该属性显示指定。

3、order:如果配置文件中定义了多个PropertyPlaceholderConfigurer,则通过该属性指定优先顺序。

4、placeholderPrefix:在上面的例子中,我们通过${属性名}引用属性文件中的属性项。其中“${”为默认的占位前符前缀,可以根据需要改为其他的前缀符。

5、placeholderSuffix:占位符后缀,默认为“}”。



使用加密的属性文件:

对于一些对安全要求特别高的应用系统(如电信、银行。公安的重点人口库等),这些敏感信息应该只掌握在少数特定维护人员手中,而不是毫无保留的对所有可以进入部署机器的人员开放。这就要求对应用程序配置文件的某些属性进行加密,让Spring容器在读取属性文件后,在内存中对属性进行解密,然后再将解密后的属性值赋给目标对象。

下面我们就来定义一个DES加密解密工具类(DES属于对称加密)

  1. package com.baobaotao.placeholder;  
  2.   
  3. import java.security.Key;  
  4. import java.security.SecureRandom;  
  5.   
  6. import javax.crypto.Cipher;  
  7. import javax.crypto.KeyGenerator;  
  8.   
  9. import sun.misc.BASE64Decoder;  
  10. import sun.misc.BASE64Encoder;  
  11. /**  
  12.  * 加密解密工具类  
  13.  * @author benjamin  
  14.  * @link 449261417@qq.com  
  15.  */  
  16. public class DESUtils {  
  17.     //密钥  
  18.     private static Key key ;  
  19.     private static String KEY_STR = "myKey" ;  
  20.       
  21.     static {  
  22.         try {  
  23.             KeyGenerator generator = KeyGenerator.getInstance("DES") ;  
  24.             generator.init(new SecureRandom(KEY_STR.getBytes())) ;  
  25.             key = generator.generateKey() ;  
  26.             generator = null ;  
  27.         } catch (Exception e) {  
  28.         }  
  29.     }  
  30.     //对字符串进行DES加密,返回BASE64编码的加密字符串  
  31.     public static String getEncryptString(String str) {  
  32.         BASE64Encoder base64en = new BASE64Encoder() ;  
  33.         try {  
  34.             byte[] strBytes = str.getBytes("UTF-8") ;  
  35.             Cipher cipher = Cipher.getInstance("DES") ;  
  36.             cipher.init(Cipher.ENCRYPT_MODE, key) ;  
  37.             byte[] encryptStrBytes = cipher.doFinal(strBytes) ;  
  38.             return base64en.encode(encryptStrBytes) ;  
  39.         } catch (Exception e) {  
  40.             throw new RuntimeException(e) ;  
  41.         }  
  42.     }  
  43.     //对BASE64编码的加密字符串进行解密,返回解密后的字符串  
  44.     public static String getDescryptString(String str) {  
  45.         BASE64Decoder base64de = new BASE64Decoder() ;  
  46.         try {  
  47.             byte[] strBytes = base64de.decodeBuffer(str) ;  
  48.             Cipher cipher = Cipher.getInstance("DES") ;  
  49.             cipher.init(Cipher.DECRYPT_MODE, key) ;  
  50.             byte[] decryptStrBytes = cipher.doFinal(strBytes) ;  
  51.             return new String(decryptStrBytes, "UTF-8") ;  
  52.         } catch (Exception e) {  
  53.             throw new RuntimeException(e) ;  
  54.         }  
  55.     }  
  56.     public static void main(String[] args) {  
  57.         if(args == null || args.length < 1) {  
  58.             System.out.println("清输入要加密的字符,用空格分隔。");  
  59.         } else {  
  60.             for(String arg : args) {  
  61.                 System.out.println(arg + ":" + getEncryptString(arg));  
  62.             }  
  63.         }  
  64.     }  
  65. }  


输入参数:root   123456运行main方法,得到下面的结果:

root:WnplV/ietfQ=
123456:QAHlVoUc49w=


把这个加密的结果改变到jdbc.properties的userName和password中

  1. driverClassName=com.mysql.jdbc.Driver  
  2. url=jdbc:mysql://localhost:3306/wiseclient  
  3. userName=WnplV/ietfQ=  
  4. password=QAHlVoUc49w=  

PropertyPlaceholderConfigurer本身不支持密文版的属性文件,不过我们扩展该类,覆盖String convertProperty(String propertyName, String propertyValue)方法,对userNamne及password的属性进行解密转换:


  1. package com.baobaotao.placeholder;  
  2.   
  3. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;  
  4.   
  5. public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{  
  6.     private String[] encryptPropNames = {"userName", "password"} ;  
  7.       
  8.     @Override  
  9.     protected String convertProperty(String propertyName, String propertyValue) {  
  10.         System.out.println("propertyName:" + propertyName + ";propertyValue:" + propertyValue);  
  11.         if(isEncryptProp(propertyName)) {  
  12.             String decryptValue = DESUtils.getDescryptString(propertyValue) ;  
  13.             System.out.println("进来解密:" + decryptValue);  
  14.             return decryptValue ;  
  15.         } else {  
  16.             return propertyValue ;  
  17.         }  
  18.     }  
  19.       
  20.     private boolean isEncryptProp(String propertyName) {  
  21.         for(String encryptPropName : encryptPropNames) {  
  22.             if(encryptPropName.equals(propertyName)) {  
  23.                 return true ;  
  24.             }  
  25.         }  
  26.         return false ;  
  27.     }  
  28.       
  29. }  


这样我们把applicationContext.xml中的配置改变一下:

  1.  //类变为我们自定义的<span style="font-family: 'Comic Sans MS';">EncryptPropertyPlaceholderConfigurer</span>  
  1. <bean class="com.baobaotao.placeholder.EncryptPropertyPlaceholderConfigurer"  
  2.         p:location="classpath:com/baobaotao/placeholder/jdbc.properties"  
  3.         p:fileEncoding="utf-8"/>  
  4.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  5.         destroy-method="close"  
  6.         p:driverClassName="${driverClassName}"  
  7.         p:url="${url}"  
  8.         p:username="${username}"  
  9.         p:password="${password}"/>  

启动容器,发现打印出这样的内容:


这样我们就完成了加密字符串在容器启动的时候解密的操作。


引用Bean的属性值:

将应用系统的配置信息放在配置文件中并非总是合适的。如果应用系统是以集群方式部署的,或者希望在运行期动态调整应用系统的某些配置,这是,将配置信息放到数据库中不但方便集中管理,而且可以通过应用系统的管理界面动态维护,有效增强应用系统的可维护性,方便管理。

下面是提供配置信息的类:

  1. package com.baobaotao.beanprop;  
  2.   
  3.   
  4.   
  5. public class SysConfig {  
  6.     private int sessionTimeout ;  
  7.     private int maxTabPageNum ;  
  8.       
  9.     public void initFromDB() {  
  10.         //模拟从数据库获取配置值  
  11.         System.out.println("从数据库中拿到相应的属性值。");  
  12.         this.sessionTimeout = 30 ;  
  13.         this.maxTabPageNum = 10 ;  
  14.     }  
  15.   
  16.     public int getSessionTimeout() {  
  17.         return sessionTimeout;  
  18.     }  
  19.   
  20.     public void setSessionTimeout(int sessionTimeout) {  
  21.         this.sessionTimeout = sessionTimeout;  
  22.     }  
  23.   
  24.     public int getMaxTabPageNum() {  
  25.         return maxTabPageNum;  
  26.     }  
  27.   
  28.     public void setMaxTabPageNum(int maxTabPageNum) {  
  29.         this.maxTabPageNum = maxTabPageNum;  
  30.     }  
  31.       
  32. }  

ApplicationContext.xml增加两行配置:

  1. <bean id="sysConfig" class="com.baobaotao.beanprop.SysConfig"   
  2.     init-method="initFromDB"/>  
  3.       
  4.    <bean class="com.baobaotao.beanprop.ApplicationManager"   
  5.     p:maxTabPageNum="#{sysConfig.maxTabPageNum}"  
  6.     p:sessionTimeout="#{sysConfig.sessionTimeout}"/>  

  1. package com.baobaotao.beanprop;  
  2.   
  3.   
  4. public class ApplicationManager {  
  5.     private int sessionTimeout ;  
  6.     private int maxTabPageNum ;  
  7.     public int getSessionTimeout() {  
  8.         return sessionTimeout;  
  9.     }  
  10.     public void setSessionTimeout(int sessionTimeout) {  
  11.         System.out.println("注入进来的sessionTimeout为:" + sessionTimeout);  
  12.         this.sessionTimeout = sessionTimeout;  
  13.     }  
  14.     public int getMaxTabPageNum() {  
  15.         return maxTabPageNum;  
  16.     }  
  17.     public void setMaxTabPageNum(int maxTabPageNum) {  
  18.         System.out.println("注入进来的maxTabPageNum为:" + maxTabPageNum);  
  19.         this.maxTabPageNum = maxTabPageNum;  
  20.     }  
  21.       
  22. }  

运行后容器输出:

从数据库中拿到相应的属性值。
注入进来的maxTabPageNum为:10
注入进来的sessionTimeout为:30


同时也可以利用@Value注解:

ApplicationContext.xml只需要一行配置:

  1. <bean id="sysConfig" class="com.baobaotao.beanprop.SysConfig"   
  2.         init-method="initFromDB"/>  

  1. package com.baobaotao.beanprop;  
  2.   
  3. import org.springframework.beans.factory.annotation.Value;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. public class ApplicationManager {  
  8.     private int sessionTimeout ;  
  9.     private int maxTabPageNum ;  
  10.     public int getSessionTimeout() {  
  11.         return sessionTimeout;  
  12.     }  
  13.     @Value("#{sysConfig.sessionTimeout}")  
  14.     public void setSessionTimeout(int sessionTimeout) {  
  15.         System.out.println("注入进来的sessionTimeout为:" + sessionTimeout);  
  16.         this.sessionTimeout = sessionTimeout;  
  17.     }  
  18.     public int getMaxTabPageNum() {  
  19.         return maxTabPageNum;  
  20.     }  
  21.     @Value("#{sysConfig.maxTabPageNum}")  
  22.     public void setMaxTabPageNum(int maxTabPageNum) {  
  23.         System.out.println("注入进来的maxTabPageNum为:" + maxTabPageNum);  
  24.         this.maxTabPageNum = maxTabPageNum;  
  25.     }  
  26.       
  27. }  

同样可以输出上面的内容。


国际化信息:

国际化资源文件的命名规范规定资源名称采用以下的方式进行命名:

<资源名>_<语言代码>_<国家/地区代码>.properties


小例子:

把下面的两个文件直接放在src目录下:

resource_en_US.properties

  1. greeting.common=How are you!  
  2. greeting.morning=Good morning!  
  3. greeting.afternoon=Good Afternoon!  

resource_zh_CN.properties

  1. greeting.common=\u60A8\u597D\uFF01  
  2. greeting.morning=\u65E9\u4E0A\u597D\uFF01  
  3. greeting.afternoon=\u4E0B\u5348\u597D\uFF01  

上面的三个属性值分别是“您好!”,“早上好!”,“下午好!”


  1. package com.baobaotao.test;  
  2.   
  3. import java.util.Locale;  
  4. import java.util.ResourceBundle;  
  5.   
  6. public class Test {  
  7.     public static void main(String[] args) {  
  8.         ResourceBundle rb1 = ResourceBundle.getBundle("resource", Locale.US) ;  
  9.         ResourceBundle rb2 = ResourceBundle.getBundle("resource", Locale.CHINA) ;  
  10.         System.out.println("us:" + rb1.getString("greeting.common"));  
  11.         System.out.println("cn:" + rb2.getString("greeting.common"));  
  12.     }  
  13. }  

输出:us:How are you!
  cn:您好!


上面的例子中,假设我们使用ResourceBundle.getBundle("resource",Locale.CANADA) 加载资源,由于不存在resource_en_CA.properties资源文件,它将尝试加载resource_zh_CN.properties的资源文件,假设resource_zh_CN.properties资源文件也不存在,它将继续尝试加载resource.properties的资源文件,如果这些资源都不存在,将抛出java.util.MissingResourceException异常。


在资源文件中使用格式化串

  1. greeting.common=How are you\!{0},today is {1}  
  2. greeting.morning=Good morning\!{0},now is {1}  
  3. greeting.afternoon=Good Afternoon\!{0} now is {1}  

  1. greeting.common=\u60A8\u597D\uFF01{0}\uFF0C\u4ECA\u5929\u662F{1}  
  2. greeting.morning=\u65E9\u4E0A\u597D\uFF01{0}\uFF0C\u73B0\u5728\u662F{1}  
  3. greeting.afternoon=\u4E0B\u5348\u597D\uFF01{0} \u73B0\u5728\u662F{1}  

  1. package com.baobaotao.test;  
  2.   
  3. import java.text.MessageFormat;  
  4. import java.util.GregorianCalendar;  
  5. import java.util.Locale;  
  6. import java.util.ResourceBundle;  
  7.   
  8. public class Test {  
  9.     public static void main(String[] args) {  
  10.         ResourceBundle rb1 = ResourceBundle.getBundle("resource", Locale.US) ;  
  11.         ResourceBundle rb2 = ResourceBundle.getBundle("resource", Locale.CHINA) ;  
  12.         Object[] params = {"John", new GregorianCalendar().getTime()} ;  
  13.           
  14.         String str1 = new MessageFormat(rb1.getString("greeting.common"),Locale.US).format(params) ;  
  15.         String str2 = new MessageFormat(rb2.getString("greeting.morning"),Locale.CHINA).format(params) ;  
  16.         String str3 = new MessageFormat(rb2.getString("greeting.afternoon"),Locale.CHINA).format(params) ;  
  17.         System.out.println(str1);  
  18.         System.out.println(str2);  
  19.         System.out.println(str3);  
  20.     }  
  21. }  

输出:How are you!John,today is 12/19/14 11:43 AM
  早上好!John,现在是14-12-19 上午11:43
  下午好!John 现在是14-12-19 上午11:43


MessageResource

在Spring中通过ResouceBundleMessageResource访配置国际化信息

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.     http://www.springframework.org/schema/context   
  9.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  10.     <bean id="myResource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  11.         <property name="basenames">  
  12.             <list>  
  13.                 <value>com/baobaotao/i18n/resource</value>  
  14.             </list>  
  15.         </property>  
  16.     </bean>  
  17. </beans>  

  1. package com.baobaotao.i18n;  
  2.   
  3. import java.util.GregorianCalendar;  
  4. import java.util.Locale;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.MessageSource;  
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  9.   
  10. public class TestResource {  
  11.     public static void main(String[] args) {  
  12.         String[] configs = {"com/baobaotao/i18n/beans.xml"} ;  
  13.         ApplicationContext ctx = new ClassPathXmlApplicationContext(configs) ;  
  14.         //获取MessageSource的Bean  
  15.         MessageSource ms = (MessageSource)ctx.getBean("myResource") ;  
  16.         Object[] params = {"John", new GregorianCalendar().getTime()} ;  
  17.         //获取格式化的国际化信息  
  18.         String str1 = ms.getMessage("greeting.common", params, Locale.US) ;  
  19.         String str2 = ms.getMessage("greeting.morning", params, Locale.CHINA) ;  
  20.         String str3 = ms.getMessage("greeting.afternoon", params, Locale.CHINA) ;  
  21.         System.out.println(str1);  
  22.         System.out.println(str2);  
  23.         System.out.println(str3);  
  24.           
  25.     }  
  26. }  

输出:How are you!John,today is 12/19/14 11:59 AM
  早上好!John,现在是14-12-19 上午11:59
  下午好!John 现在是14-12-19 上午11:59


我们也可以通过使用ReloadableResourceBundleMessageSource

它和ResourceBundleMessageSource的唯一区别在于它可以定时刷新资源文件,以便在应用程序不重启的情况下感知资源文件的变化。

  1. <bean id="myResource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
  2.         <property name="basenames">  
  3.             <list>  
  4.                 <value>com/baobaotao/i18n/resource</value>  
  5.             </list>  
  6.         </property>  
  7.         <property name="cacheSeconds" value="5"></property>  
  8.     </bean>  

在上面的配置中,我们通过cacheSeconds属性让ReloadableResourceBundleMessageSource每5秒刷新一次资源文件(在真实应用中,刷新周期不能太短,否则频繁的刷新将带来性能上的负面影响,一般不建议小于30分钟)。cacheSeconds默认值为-1表示永不刷新。


容器级的国际化信息资源

在配置文件中名称为"messageSource“且类型为org.springframework.context.MessageSource的Bean,会被加载为容器级的国际化信息资源。

  1. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  2.         <property name="basenames">  
  3.             <list>  
  4.                 <value>com/baobaotao/i18n/resource</value>  
  5.             </list>  
  6.         </property>  
  7.     </bean>  

  1. package com.baobaotao.i18n;  
  2.   
  3. import java.util.GregorianCalendar;  
  4. import java.util.Locale;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.MessageSource;  
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  9.   
  10. public class TestResource {  
  11.     public static void main(String[] args) {  
  12.         String[] configs = {"com/baobaotao/i18n/beans.xml"} ;  
  13.         ApplicationContext ctx = new ClassPathXmlApplicationContext(configs) ;  
  14.         Object[] params = {"John", new GregorianCalendar().getTime()} ;  
  15.         //获取格式化的国际化信息  
  16.         String str1 = ctx.getMessage("greeting.common", params, Locale.US) ;  
  17.         String str2 = ctx.getMessage("greeting.morning", params, Locale.CHINA) ;  
  18.         String str3 = ctx.getMessage("greeting.afternoon", params, Locale.CHINA) ;  
  19.         System.out.println(str1);  
  20.         System.out.println(str2);  
  21.         System.out.println(str3);  
  22.           
  23.     }  
  24. }  

输出:How are you!John,today is 12/19/14 5:59 PM
  早上好!John,现在是14-12-19 下午5:59
  下午好!John 现在是14-12-19 下午5:59


下面是一个事件的发布和监听的例子:

  1. package com.baobaotao.event;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.event.ApplicationContextEvent;  
  5.   
  6. @SuppressWarnings("serial")  
  7. public class MailSendEvent extends ApplicationContextEvent{  
  8.     private String to ;  
  9.       
  10.     public MailSendEvent(ApplicationContext source, String to) {  
  11.         super(source);  
  12.         this.to = to ;  
  13.     }  
  14.       
  15.     public String getTo() {  
  16.         return this.to ;  
  17.     }  
  18.       
  19. }  

  1. package com.baobaotao.event;  
  2.   
  3. import org.springframework.context.ApplicationListener;  
  4.   
  5. public class MailSendListener implements ApplicationListener<MailSendEvent>{  
  6.   
  7.     public void onApplicationEvent(MailSendEvent event) {  
  8.         MailSendEvent mse = (MailSendEvent)event ;  
  9.         System.out.println("MailSendListener:向" + mse.getTo() + "发送完一封邮件");  
  10.     }  
  11.   
  12. }  

  1. package com.baobaotao.event;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.ApplicationContextAware;  
  6.   
  7. public class MailSender implements ApplicationContextAware{  
  8.     private ApplicationContext ctx ;  
  9.       
  10.     public void setApplicationContext(ApplicationContext ctx)  
  11.             throws BeansException {  
  12.         this.ctx = ctx ;  
  13.     }  
  14.       
  15.     public void sendMail(String to) {  
  16.         System.out.println("MailSender:模拟发送邮件...");  
  17.         MailSendEvent mse = new MailSendEvent(this.ctx, to) ;  
  18.         ctx.publishEvent(mse) ;  
  19.     }  
  20.   
  21. }  

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.     http://www.springframework.org/schema/context   
  9.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  10.     <bean class="com.baobaotao.event.MailSendListener" />  
  11.     <bean id="mailSender" class="com.baobaotao.event.MailSender" />  
  12. </beans>  

  1. package com.baobaotao.event;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class TestSendMail {  
  7.     public static void main(String[] args) {  
  8.         ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml") ;  
  9.         MailSender mailSender = (MailSender)ctx.getBean("mailSender") ;  
  10.         mailSender.sendMail("449261417@qq.com") ;   
  11.     }  
  12. }  

输出结果为:MailSender:模拟发送邮件...
    MailSendListener:向449261417@qq.com发送完一封邮件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值