Ioc概念:
包括两个内容:控制&反转
对于软件来说,是某一接口具体实现类的选择控制权从调用类中移除,转交给第三方决定。DI(依赖注入:Dependency Injection)即让调用类对某一接口实现类的依赖由第三方(容器或协作类)注入,以移除调用类对某一接口实现类的依赖。
Ioc类型:从注入方法上看,主要可以划分为三种类型:构造函数注入、属性注入和接口注入。
反射在Ioc中的应用,小例子:
Car.class
- package com.wiseweb.ioc;
-
- public class Car {
-
- private String brand ;
-
- private String color ;
-
- private int maxSpeed ;
-
- public Car(){}
-
- public Car(String brand, String color, int maxSpeed) {
- this.brand = brand ;
- this.color = color ;
- this.maxSpeed = maxSpeed ;
- }
-
- public void introduce() {
- System.out.println("brand:" + brand + ";color:" +color + ";maxSpeed" + maxSpeed);
- }
- public String getBrand() {
- return brand;
- }
- public void setBrand(String brand) {
- this.brand = brand;
- }
- public String getColor() {
- return color;
- }
- public void setColor(String color) {
- this.color = color;
- }
- public int getMaxSpeed() {
- return maxSpeed;
- }
- public void setMaxSpeed(int maxSpeed) {
- this.maxSpeed = maxSpeed;
- }
-
- }
ReflectTest.class
- package com.wiseweb.ioc;
-
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
-
- public class ReflectTest {
- public static Car initByDefaultConst() throws Throwable {
- ClassLoader loader = Thread.currentThread().getContextClassLoader() ;
- Class clazz = loader.loadClass("com.wiseweb.ioc.Car") ;
-
- Constructor cons = clazz.getDeclaredConstructor((Class[])null) ;
- Car car = (Car)cons.newInstance() ;
-
- Method setBrand = clazz.getMethod("setBrand", String.class) ;
- setBrand.invoke(car, "红旗") ;
- Method setColor = clazz.getMethod("setColor", String.class) ;
- setColor.invoke(car, "黑色") ;
- Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class) ;
- setMaxSpeed.invoke(car, 200) ;
- return car ;
- }
-
- public static void main(String[] args) throws Throwable {
- Car car = initByDefaultConst() ;
- car.introduce() ;
- }
- }
输出: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装载应用程序的类。
- package com.wiseweb.ioc;
-
- public class ClassLoaderTest {
- public static void main(String[] args) {
- ClassLoader loader = Thread.currentThread().getContextClassLoader() ;
- System.out.println("current loader:" + loader);
- System.out.println("parent loader:" + loader.getParent());
- System.out.println("grandparent loader:" + loader.getParent().getParent());
- }
- }
输出: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应用根目录的方式进行访问。
- package com.wiseweb.ioc;
-
- import java.io.IOException;
- import java.io.InputStream;
-
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.FileSystemResource;
- import org.springframework.core.io.Resource;
-
-
- public class FileSourceExample {
- public static void main(String[] args) {
- try {
- String filePath = "F:/workspace/httpClient/src/conf/file1.txt" ;
- Resource res1 = new FileSystemResource(filePath) ;
- Resource res2 = new ClassPathResource("conf/file1.txt") ;
-
- InputStream ins1 = res1.getInputStream() ;
- InputStream ins2 = res2.getInputStream() ;
- System.out.println("res1: " + res1.getFilename());
- System.out.println("res2: " + res2.getFilename());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
输出:res1: file1.txt
res2: file1.txt
资源加载时默认采用系统编码读取资源内容,如果资源文件采用特殊的编码格式,那么可以通过EncodedResource对资源进行编码,以保证资源内容操作的正确性。
- package com.wiseweb.ioc;
-
- import java.io.File;
- import java.io.FileWriter;
-
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- import org.springframework.core.io.support.EncodedResource;
- import org.springframework.util.FileCopyUtils;
-
- public class EncodedResourceExample {
- public static void main(String[] args) throws Throwable {
- Resource res = new ClassPathResource("conf/file1.txt") ;
- EncodedResource encRes = new EncodedResource(res, "utf-8") ;
- String content = FileCopyUtils.copyToString(encRes.getReader()) ;
- System.out.println(content);
- File f = new File("d:/a.txt") ;
- FileWriter fw = new FileWriter(f) ;
- //Spring的文件copy,传入一个输入流,一个输出流。
- FileCopyUtils.copy(encRes.getReader(), fw) ;
- }
- }
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后支持类注解的配置方式:
- package com.baobaotao.entity;
-
- public class Car {
- private String brand ;
- private String color ;
- private int maxSpeed ;
-
- public Car() {
- super();
- }
- public Car(String brand, String color, int maxSpeed) {
- super();
- this.brand = brand;
- this.color = color;
- this.maxSpeed = maxSpeed;
- }
- public String getBrand() {
- return brand;
- }
- public void setBrand(String brand) {
- this.brand = brand;
- }
- public String getColor() {
- return color;
- }
- public void setColor(String color) {
- this.color = color;
- }
- public int getMaxSpeed() {
- return maxSpeed;
- }
- public void setMaxSpeed(int maxSpeed) {
- this.maxSpeed = maxSpeed;
- }
-
- public void introduce() {
- System.out.println("brand:" + brand + ";color" + color + ";maxSpeed" + maxSpeed);
- }
- }
- package com.baobaotao.context;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- import com.baobaotao.entity.Car;
- //表示这是一个配置信息提供类
- @Configuration
- public class Beans {
- //定义一个Bean
- @Bean(name="car")
- public Car buildCar() {
- Car car = new Car() ;
- car.setBrand("红旗CA72") ;
- car.setMaxSpeed(200) ;
- return car ;
- }
- }
- package com.baobaotao.context;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-
- import com.baobaotao.entity.Car;
-
- public class AnnotationApplicationContext {
- public static void main(String[] args) {
- ApplicationContext ctx = new AnnotationConfigApplicationContext(Beans.class) ;
- Car car = ctx.getBean("car", Car.class) ;
- System.out.println(car.getBrand());
- }
- }
WebApplicationCOntext是专门为Web应用准备的,它允许从相对于Web根目录的路径中装载配置文件完成初始化工作。从WebApplicationContext中可以获得ServletContext的引用,整个Web应用上下文对象将最为属性放置到ServletContext中,以便Web应用环境可以访问Spring应用上下文。
WebApplicationContext定义了一个常量ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,在上下文启动时,WebApplicationContext实例即以此为键放置在ServletContext的属性列表中,因此我们可以直接通过以下语句从web容器中获取WebApplicationContext:
- WebApplicationContext wac = (WebApplicationContext)servletContext.
- getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) ;
WebApplicationContext的初始化方式和BeanFactory、ApplicationContext有所区别,因为WebApplicationCOntext需要ServletContext实例,也就是说它必须在拥有Web容器的前提下才能完成启动的工作。有过Web开发经验的人都知道在web.xml中配置自启动的Servlet或定义Web容器监听器(ServletContextListener),借助这两者中的任何一个,我们就可以完成启动Spring Web应用上下文的工作。
下面是使用ContextLoaderListener启动WebApplicationContext的具体配置:
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/baobaotao.xml,/WEB-INF/baobaotao-service.xml
- </param-value>
- </context-param>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
如果使用Web监听器,则必须将Log4jConfigListener防止在ContextLoaderListener的前面。采用下面的配置方式Spring将自动使用XmlWebApplicationContext启动Spring容器,即通过XML文件为Spring容器提供Bean的配置信息。
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>WEB-INF/log4j.properties</param-value>
- </context-param>
-
- <context-param>
- <param-name>log4jRefreshInterval</param-name>
- <param-value>60000</param-value>
- </context-param>
-
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
如果使用@Configuration的Java类提供配置信息,则web.xml的配置需要按以下方式配置:
- <context-param>
- <param-name>contextClass</param-name>
- <param-value>
- org.springframework.web.context.support.AnnotationConfigWebApplicationContext
- </param-value>
- </context-param>
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>com.baobaotao.AppConfig1,com.baobaotao.AppConfig2</param-value>
- </context-param>
-
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
Bean的生命周期:
下面用例子说明BeanFactory中Bean的生命周期:
- package com.baobaotao.entity;
-
- import org.springframework.beans.BeansException;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.BeanFactoryAware;
- import org.springframework.beans.factory.BeanNameAware;
- import org.springframework.beans.factory.DisposableBean;
- import org.springframework.beans.factory.InitializingBean;
- //管理bean生命周期的接口
- public class Car implements BeanFactoryAware,BeanNameAware,InitializingBean,DisposableBean{
- private String brand ;
- private String color ;
- private int maxSpeed ;
- private BeanFactory beanFactory ;
- private String beanName ;
-
- public Car() {
- super();
- System.out.println("调用car构造函数。");
- }
- public String getBrand() {
- return brand;
- }
- public void setBrand(String brand) {
- System.out.println("设置setBrand()设置属性。");
- this.brand = brand;
- }
- public String getColor() {
- return color;
- }
- public void setColor(String color) {
- this.color = color;
- }
- public int getMaxSpeed() {
- return maxSpeed;
- }
- public void setMaxSpeed(int maxSpeed) {
- this.maxSpeed = maxSpeed;
- }
-
- public void introduce() {
- System.out.println("brand:" + brand + ";color" + color + ";maxSpeed" + maxSpeed);
- }
- //BeanFactoryAware接口方法
- public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
- System.out.println("调用BeanFactoryAware.setBeanFactory()。");
- this.beanFactory = beanFactory ;
- }
- //BeanNameAware接口方法
- public void setBeanName(String beanName) {
- System.out.println("调用BeanNameAware.setBeanName()。");
- this.beanName = beanName ;
- }
- //InitializongBean接口方法
- public void afterPropertiesSet() throws Exception {
- System.out.println("调用InitilizingBean.afterPropertiesSet()。");
- }
- //DisposableBean接口方法
- public void destroy() throws Exception {
- System.out.println("调用DisposableBean.destroy()。");
- }
- //通过<bean>的init-method属性指定的初始化方法
- public void myInit() {
- System.out.println("调用init-method所指定的myInit(),将maxSpeed设置为240。");
- this.maxSpeed = 240 ;
- }
- //通过<bean>的destroy-method属性指定的销毁方法
- public void myDestroy() {
- System.out.println("destroy-method所指定的myDestroy()。");
- }
- }
- package com.baobaotao.beanfactory;
-
- import java.beans.PropertyDescriptor;
-
- import org.springframework.beans.BeansException;
- import org.springframework.beans.PropertyValues;
- import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
-
- public class MyInstantiationAwarePostProcessor extends InstantiationAwareBeanPostProcessorAdapter{
- //接口方法,在实例化后调用
- @Override
- public boolean postProcessAfterInstantiation(Object bean, String beanName)
- throws BeansException {
- if("car".equals(beanName)) {
- System.out.println("InstantiationAware BeanPostProcessor.postProcessAfterInstantiation");
- }
- return super.postProcessAfterInstantiation(bean, beanName);
- }
- //接口方法,在实例化Bean前调用
- @Override
- public Object postProcessBeforeInstantiation(Class<?> beanClass,
- String beanName) throws BeansException {
- if("car".equals(beanName)) {
- System.out.println("InstantiationAware BeanPostProcessor.postProcessBeforeInstantiation");
- }
- return null;
- }
- //接口方法,在设置某个属性时调用
- @Override
- public PropertyValues postProcessPropertyValues(PropertyValues pvs,
- PropertyDescriptor[] pds, Object bean, String beanName)
- throws BeansException {
- if("car".equals(beanName)) {
- System.out.println("InstantiationAware BeanPostProcessor.postProcessPropertyValues");
- }
- return pvs;
- }
-
- }
- package com.baobaotao.beanfactory;
-
- import org.springframework.beans.BeansException;
- import org.springframework.beans.factory.config.BeanPostProcessor;
-
- import com.baobaotao.entity.Car;
-
- public class MyBeanPostProcessor implements BeanPostProcessor{
-
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
- if(beanName.equals("car")) {
- Car car = (Car)bean ;
- if(car.getColor() == null) {
- System.out.println("调用BeanPostProcessor.postProcessBeforeInitialization()," +
- "color为空,设置为默认黑色。");
- car.setColor("黑色") ;
- }
- }
- return bean;
- }
-
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if(beanName.equals("car")) {
- Car car = (Car)bean ;
- if(car.getMaxSpeed() >= 200) {
- System.out.println("调用BeanPostProcessor.postProcessAfterInitialization()," +
- "将maxSpeed调正为200。");
- car.setMaxSpeed(200) ;
- }
- }
- return bean;
- }
-
-
-
-
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- 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
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean id="car" class="com.baobaotao.entity.Car" init-method="myInit"
- destroy-method="myDestroy" scope="singleton">
- <property name="brand" value="红旗CA72"></property>
- <property name="maxSpeed" value="200"></property>
- </bean>
- </beans>
- package com.baobaotao.beanfactory;
-
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.config.ConfigurableBeanFactory;
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
-
- import com.baobaotao.entity.Car;
-
- public class BeanLifeCycle {
- @SuppressWarnings("deprecation")
- public static void LifeCycleBeanFactory() {
- Resource res = new ClassPathResource("com/baobaotao/beanfactory/beans.xml") ;
- BeanFactory bf = new XmlBeanFactory(res) ;
- ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyBeanPostProcessor()) ;
- ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyInstantiationAwarePostProcessor()) ;
- //第一次从容器中获取car,将出发容器实例化该Bean,这将引发Bean生命周期方法的调用
- Car car1 = (Car)bf.getBean("car") ;
- car1.introduce() ;
- car1.setColor("红色") ;
-
- //第二次从容器中获取car,直接从缓存池中获取
- Car car2 = (Car)bf.getBean("car") ;
- System.out.println("car1==car2:" + (car1==car2));
- //关闭容器
- ((XmlBeanFactory)bf).destroySingletons() ;
- }
- public static void main(String[] args) {
- LifeCycleBeanFactory() ;
- }
- }
输出:
- InstantiationAware BeanPostProcessor.postProcessBeforeInstantiation
- 调用car构造函数。
- InstantiationAware BeanPostProcessor.postProcessAfterInstantiation
- InstantiationAware BeanPostProcessor.postProcessPropertyValues
- 设置setBrand()设置属性。
- 调用BeanNameAware.setBeanName()。
- 调用BeanFactoryAware.setBeanFactory()。
- 调用BeanPostProcessor.postProcessBeforeInitialization(),color为空,设置为默认黑色。
- 调用InitilizingBean.afterPropertiesSet()。
- 调用init-method所指定的myInit(),将maxSpeed设置为240。
- 调用BeanPostProcessor.postProcessAfterInitialization(),将maxSpeed调正为200。
- brand:红旗CA72;color黑色;maxSpeed200
- car1==car2:true
- 调用DisposableBean.destroy()。
- destroy-method所指定的myDestroy()。
如果配置文件中定义了多个工厂后处理器,最好让它们实现org.springframework.core.Ordered接口,以便Spring以确定的顺序调用它们。
ApplicationContext和BeanFactory一个最大的不同之处在于:前者会利用Java反射机制自动识别出配置文件中定义的BeanPostProcessor、InstantiationAwareBeanPostProcess和BeanFactoryProcessor,并自动将它们注册到应用上下文中;而后者需要在代码中通过手工调用addBeanPostProcessor()方法进行注册。这也是为什么在应用开发时,我们普遍使用ApplicationContext而很少使用BeanFactory的原因之一。
总结:
控制反转:
“控制”是接口实现类的选择控制权
“反转”是指这种选择控制权从调用类转移到外部第三方类或容器的手中
依赖注入参数详解:
- <bean id="car" class="com.baobaotao.entity.Car">
- <property name="maxSpeed">
- <value>200</value>
- </property>
- <property name="brand">
- <value><![CDATA[红旗&CA72]]></value>
- </property>
- </bean>
上面代码中的brand属性值包含了一个XML的特殊符号,因此我在属性值外加了一个<![CDATA[]]>的XML特殊处理标签,<![CDATA[]]>的作用是让XML解析器将标签中的字符串当作普通的文本对待,以防止某些字符串对XML格式造成破坏。
XML中共有5个特殊的字符,分别是:&<>"',上面所说的是一种解决办法,还有一种是使用XML转义序列表示这些特殊的字符,下面定义了这些特殊字符对应的转义序列:
< <
>>
&&
""
''
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()方法就可以了。
- package com.baobaotao.editor;
-
- public class Car {
- private int maxSpeed ;
- private String brand ;
- private double price ;
- public int getMaxSpeed() {
- return maxSpeed;
- }
- public void setMaxSpeed(int maxSpeed) {
- System.out.println("maxSpeed注入进来:" + maxSpeed);
- this.maxSpeed = maxSpeed;
- }
- public String getBrand() {
- return brand;
- }
- public void setBrand(String brand) {
- System.out.println("brand注入进来:" + brand);
- this.brand = brand;
- }
- public double getPrice() {
- return price;
- }
- public void setPrice(double price) {
- System.out.println("price注入进来:" + price);
- this.price = price;
- }
-
-
- }
- package com.baobaotao.editor;
-
- public class Boss {
- private String name ;
- private Car car = new Car() ;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Car getCar() {
- return car;
- }
- public void setCar(Car car) {
- this.car = car;
- }
-
- }
- package com.baobaotao.editor;
-
- import java.beans.PropertyEditorSupport;
-
- public class CustomCarEditor extends PropertyEditorSupport{
-
- @Override
- public void setAsText(String text) {
- if(text == null || text.indexOf(",") == -1) {
- throw new IllegalArgumentException("设置的字符串格式不正确") ;
- }
- String[] infos = text.split(",") ;
- Car car = new Car() ;
- car.setBrand(infos[0]) ;
- car.setMaxSpeed(Integer.parseInt(infos[1])) ;
- car.setPrice(Double.parseDouble(infos[2])) ;
- setValue(car) ;
- }
-
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- 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
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
- <property name="customEditors">
- <map>
- <entry key="com.baobaotao.editor.Car">
- <bean class="com.baobaotao.editor.CustomCarEditor"></bean>
- </entry>
- </map>
- </property>
- </bean>
-
- <bean id="boss" class="com.baobaotao.editor.Boss">
- <property name="name" value="John" />
- <property name="car" value="红旗CA72,200,2000.00" />
- </bean>
- </beans>
- package com.baobaotao.editor;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class CustomTest {
- public static void main(String[] args) {
- ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml") ;
- Boss boss = (Boss)ac.getBean("boss") ;
- System.out.println(boss.getCar().getBrand());
- }
- }
输出:brand注入进来:红旗CA72
maxSpeed注入进来:200
price注入进来:2000.0
红旗CA72
使用外部属性文件:
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
- p:location="classpath:com/baobaotao/placeholder/jdbc.properties"
- p:fileEncoding="utf-8"/>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close"
- p:driverClassName="${driverClassName}"
- p:url="${url}"
- p:username="${username}"
- p:password="${password}"/>
PropertyPlaceholderConfigurer其他属性:
1、locations:如果只有一个属性文件,直接使用location属性指定就可以了,如果是多个属性文件,则可以通过locations属性进行设置,可以像配置List一样配置locations属性。
2、fileEncoding:属性文件的编码格式,Spring使用操作系统默认编码读取属性文件,如果属性文件采用了特殊编码,需要通过该属性显示指定。
3、order:如果配置文件中定义了多个PropertyPlaceholderConfigurer,则通过该属性指定优先顺序。
4、placeholderPrefix:在上面的例子中,我们通过${属性名}引用属性文件中的属性项。其中“${”为默认的占位前符前缀,可以根据需要改为其他的前缀符。
5、placeholderSuffix:占位符后缀,默认为“}”。
使用加密的属性文件:
对于一些对安全要求特别高的应用系统(如电信、银行。公安的重点人口库等),这些敏感信息应该只掌握在少数特定维护人员手中,而不是毫无保留的对所有可以进入部署机器的人员开放。这就要求对应用程序配置文件的某些属性进行加密,让Spring容器在读取属性文件后,在内存中对属性进行解密,然后再将解密后的属性值赋给目标对象。
下面我们就来定义一个DES加密解密工具类(DES属于对称加密)
- package com.baobaotao.placeholder;
-
- import java.security.Key;
- import java.security.SecureRandom;
-
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
-
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- /**
- * 加密解密工具类
- * @author benjamin
- * @link 449261417@qq.com
- */
- public class DESUtils {
- //密钥
- private static Key key ;
- private static String KEY_STR = "myKey" ;
-
- static {
- try {
- KeyGenerator generator = KeyGenerator.getInstance("DES") ;
- generator.init(new SecureRandom(KEY_STR.getBytes())) ;
- key = generator.generateKey() ;
- generator = null ;
- } catch (Exception e) {
- }
- }
- //对字符串进行DES加密,返回BASE64编码的加密字符串
- public static String getEncryptString(String str) {
- BASE64Encoder base64en = new BASE64Encoder() ;
- try {
- byte[] strBytes = str.getBytes("UTF-8") ;
- Cipher cipher = Cipher.getInstance("DES") ;
- cipher.init(Cipher.ENCRYPT_MODE, key) ;
- byte[] encryptStrBytes = cipher.doFinal(strBytes) ;
- return base64en.encode(encryptStrBytes) ;
- } catch (Exception e) {
- throw new RuntimeException(e) ;
- }
- }
- //对BASE64编码的加密字符串进行解密,返回解密后的字符串
- public static String getDescryptString(String str) {
- BASE64Decoder base64de = new BASE64Decoder() ;
- try {
- byte[] strBytes = base64de.decodeBuffer(str) ;
- Cipher cipher = Cipher.getInstance("DES") ;
- cipher.init(Cipher.DECRYPT_MODE, key) ;
- byte[] decryptStrBytes = cipher.doFinal(strBytes) ;
- return new String(decryptStrBytes, "UTF-8") ;
- } catch (Exception e) {
- throw new RuntimeException(e) ;
- }
- }
- public static void main(String[] args) {
- if(args == null || args.length < 1) {
- System.out.println("清输入要加密的字符,用空格分隔。");
- } else {
- for(String arg : args) {
- System.out.println(arg + ":" + getEncryptString(arg));
- }
- }
- }
- }
输入参数:root 123456运行main方法,得到下面的结果:
root:WnplV/ietfQ=
123456:QAHlVoUc49w=
把这个加密的结果改变到jdbc.properties的userName和password中
- driverClassName=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/wiseclient
- userName=WnplV/ietfQ=
- password=QAHlVoUc49w=
PropertyPlaceholderConfigurer本身不支持密文版的属性文件,不过我们扩展该类,覆盖String convertProperty(String propertyName, String propertyValue)方法,对userNamne及password的属性进行解密转换:
- package com.baobaotao.placeholder;
-
- import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
-
- public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
- private String[] encryptPropNames = {"userName", "password"} ;
-
- @Override
- protected String convertProperty(String propertyName, String propertyValue) {
- System.out.println("propertyName:" + propertyName + ";propertyValue:" + propertyValue);
- if(isEncryptProp(propertyName)) {
- String decryptValue = DESUtils.getDescryptString(propertyValue) ;
- System.out.println("进来解密:" + decryptValue);
- return decryptValue ;
- } else {
- return propertyValue ;
- }
- }
-
- private boolean isEncryptProp(String propertyName) {
- for(String encryptPropName : encryptPropNames) {
- if(encryptPropName.equals(propertyName)) {
- return true ;
- }
- }
- return false ;
- }
-
- }
这样我们把applicationContext.xml中的配置改变一下:
- //类变为我们自定义的<span style="font-family: 'Comic Sans MS';">EncryptPropertyPlaceholderConfigurer</span>
- <bean class="com.baobaotao.placeholder.EncryptPropertyPlaceholderConfigurer"
- p:location="classpath:com/baobaotao/placeholder/jdbc.properties"
- p:fileEncoding="utf-8"/>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close"
- p:driverClassName="${driverClassName}"
- p:url="${url}"
- p:username="${username}"
- p:password="${password}"/>
启动容器,发现打印出这样的内容:
这样我们就完成了加密字符串在容器启动的时候解密的操作。
引用Bean的属性值:
将应用系统的配置信息放在配置文件中并非总是合适的。如果应用系统是以集群方式部署的,或者希望在运行期动态调整应用系统的某些配置,这是,将配置信息放到数据库中不但方便集中管理,而且可以通过应用系统的管理界面动态维护,有效增强应用系统的可维护性,方便管理。
下面是提供配置信息的类:
- package com.baobaotao.beanprop;
-
-
-
- public class SysConfig {
- private int sessionTimeout ;
- private int maxTabPageNum ;
-
- public void initFromDB() {
- //模拟从数据库获取配置值
- System.out.println("从数据库中拿到相应的属性值。");
- this.sessionTimeout = 30 ;
- this.maxTabPageNum = 10 ;
- }
-
- public int getSessionTimeout() {
- return sessionTimeout;
- }
-
- public void setSessionTimeout(int sessionTimeout) {
- this.sessionTimeout = sessionTimeout;
- }
-
- public int getMaxTabPageNum() {
- return maxTabPageNum;
- }
-
- public void setMaxTabPageNum(int maxTabPageNum) {
- this.maxTabPageNum = maxTabPageNum;
- }
-
- }
ApplicationContext.xml增加两行配置:
- <bean id="sysConfig" class="com.baobaotao.beanprop.SysConfig"
- init-method="initFromDB"/>
-
- <bean class="com.baobaotao.beanprop.ApplicationManager"
- p:maxTabPageNum="#{sysConfig.maxTabPageNum}"
- p:sessionTimeout="#{sysConfig.sessionTimeout}"/>
- package com.baobaotao.beanprop;
-
-
- public class ApplicationManager {
- private int sessionTimeout ;
- private int maxTabPageNum ;
- public int getSessionTimeout() {
- return sessionTimeout;
- }
- public void setSessionTimeout(int sessionTimeout) {
- System.out.println("注入进来的sessionTimeout为:" + sessionTimeout);
- this.sessionTimeout = sessionTimeout;
- }
- public int getMaxTabPageNum() {
- return maxTabPageNum;
- }
- public void setMaxTabPageNum(int maxTabPageNum) {
- System.out.println("注入进来的maxTabPageNum为:" + maxTabPageNum);
- this.maxTabPageNum = maxTabPageNum;
- }
-
- }
运行后容器输出:
从数据库中拿到相应的属性值。
注入进来的maxTabPageNum为:10
注入进来的sessionTimeout为:30
同时也可以利用@Value注解:
ApplicationContext.xml只需要一行配置:
- <bean id="sysConfig" class="com.baobaotao.beanprop.SysConfig"
- init-method="initFromDB"/>
- package com.baobaotao.beanprop;
-
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
-
- @Component
- public class ApplicationManager {
- private int sessionTimeout ;
- private int maxTabPageNum ;
- public int getSessionTimeout() {
- return sessionTimeout;
- }
- @Value("#{sysConfig.sessionTimeout}")
- public void setSessionTimeout(int sessionTimeout) {
- System.out.println("注入进来的sessionTimeout为:" + sessionTimeout);
- this.sessionTimeout = sessionTimeout;
- }
- public int getMaxTabPageNum() {
- return maxTabPageNum;
- }
- @Value("#{sysConfig.maxTabPageNum}")
- public void setMaxTabPageNum(int maxTabPageNum) {
- System.out.println("注入进来的maxTabPageNum为:" + maxTabPageNum);
- this.maxTabPageNum = maxTabPageNum;
- }
-
- }
同样可以输出上面的内容。
国际化信息:
国际化资源文件的命名规范规定资源名称采用以下的方式进行命名:
<资源名>_<语言代码>_<国家/地区代码>.properties
小例子:
把下面的两个文件直接放在src目录下:
resource_en_US.properties
- greeting.common=How are you!
- greeting.morning=Good morning!
- greeting.afternoon=Good Afternoon!
resource_zh_CN.properties
- greeting.common=\u60A8\u597D\uFF01
- greeting.morning=\u65E9\u4E0A\u597D\uFF01
- greeting.afternoon=\u4E0B\u5348\u597D\uFF01
上面的三个属性值分别是“您好!”,“早上好!”,“下午好!”
- package com.baobaotao.test;
-
- import java.util.Locale;
- import java.util.ResourceBundle;
-
- public class Test {
- public static void main(String[] args) {
- ResourceBundle rb1 = ResourceBundle.getBundle("resource", Locale.US) ;
- ResourceBundle rb2 = ResourceBundle.getBundle("resource", Locale.CHINA) ;
- System.out.println("us:" + rb1.getString("greeting.common"));
- System.out.println("cn:" + rb2.getString("greeting.common"));
- }
- }
输出: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异常。
在资源文件中使用格式化串
- greeting.common=How are you\!{0},today is {1}
- greeting.morning=Good morning\!{0},now is {1}
- greeting.afternoon=Good Afternoon\!{0} now is {1}
- greeting.common=\u60A8\u597D\uFF01{0}\uFF0C\u4ECA\u5929\u662F{1}
- greeting.morning=\u65E9\u4E0A\u597D\uFF01{0}\uFF0C\u73B0\u5728\u662F{1}
- greeting.afternoon=\u4E0B\u5348\u597D\uFF01{0} \u73B0\u5728\u662F{1}
- package com.baobaotao.test;
-
- import java.text.MessageFormat;
- import java.util.GregorianCalendar;
- import java.util.Locale;
- import java.util.ResourceBundle;
-
- public class Test {
- public static void main(String[] args) {
- ResourceBundle rb1 = ResourceBundle.getBundle("resource", Locale.US) ;
- ResourceBundle rb2 = ResourceBundle.getBundle("resource", Locale.CHINA) ;
- Object[] params = {"John", new GregorianCalendar().getTime()} ;
-
- String str1 = new MessageFormat(rb1.getString("greeting.common"),Locale.US).format(params) ;
- String str2 = new MessageFormat(rb2.getString("greeting.morning"),Locale.CHINA).format(params) ;
- String str3 = new MessageFormat(rb2.getString("greeting.afternoon"),Locale.CHINA).format(params) ;
- System.out.println(str1);
- System.out.println(str2);
- System.out.println(str3);
- }
- }
输出: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访配置国际化信息
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:p="http://www.springframework.org/schema/p"
- 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
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean id="myResource" class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basenames">
- <list>
- <value>com/baobaotao/i18n/resource</value>
- </list>
- </property>
- </bean>
- </beans>
- package com.baobaotao.i18n;
-
- import java.util.GregorianCalendar;
- import java.util.Locale;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.MessageSource;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class TestResource {
- public static void main(String[] args) {
- String[] configs = {"com/baobaotao/i18n/beans.xml"} ;
- ApplicationContext ctx = new ClassPathXmlApplicationContext(configs) ;
- //获取MessageSource的Bean
- MessageSource ms = (MessageSource)ctx.getBean("myResource") ;
- Object[] params = {"John", new GregorianCalendar().getTime()} ;
- //获取格式化的国际化信息
- String str1 = ms.getMessage("greeting.common", params, Locale.US) ;
- String str2 = ms.getMessage("greeting.morning", params, Locale.CHINA) ;
- String str3 = ms.getMessage("greeting.afternoon", params, Locale.CHINA) ;
- System.out.println(str1);
- System.out.println(str2);
- System.out.println(str3);
-
- }
- }
输出: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的唯一区别在于它可以定时刷新资源文件,以便在应用程序不重启的情况下感知资源文件的变化。
- <bean id="myResource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
- <property name="basenames">
- <list>
- <value>com/baobaotao/i18n/resource</value>
- </list>
- </property>
- <property name="cacheSeconds" value="5"></property>
- </bean>
在上面的配置中,我们通过cacheSeconds属性让ReloadableResourceBundleMessageSource每5秒刷新一次资源文件(在真实应用中,刷新周期不能太短,否则频繁的刷新将带来性能上的负面影响,一般不建议小于30分钟)。cacheSeconds默认值为-1表示永不刷新。
容器级的国际化信息资源
在配置文件中名称为"messageSource“且类型为org.springframework.context.MessageSource的Bean,会被加载为容器级的国际化信息资源。
- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basenames">
- <list>
- <value>com/baobaotao/i18n/resource</value>
- </list>
- </property>
- </bean>
- package com.baobaotao.i18n;
-
- import java.util.GregorianCalendar;
- import java.util.Locale;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.MessageSource;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class TestResource {
- public static void main(String[] args) {
- String[] configs = {"com/baobaotao/i18n/beans.xml"} ;
- ApplicationContext ctx = new ClassPathXmlApplicationContext(configs) ;
- Object[] params = {"John", new GregorianCalendar().getTime()} ;
- //获取格式化的国际化信息
- String str1 = ctx.getMessage("greeting.common", params, Locale.US) ;
- String str2 = ctx.getMessage("greeting.morning", params, Locale.CHINA) ;
- String str3 = ctx.getMessage("greeting.afternoon", params, Locale.CHINA) ;
- System.out.println(str1);
- System.out.println(str2);
- System.out.println(str3);
-
- }
- }
输出:How are you!John,today is 12/19/14 5:59 PM
早上好!John,现在是14-12-19 下午5:59
下午好!John 现在是14-12-19 下午5:59
下面是一个事件的发布和监听的例子:
- package com.baobaotao.event;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.event.ApplicationContextEvent;
-
- @SuppressWarnings("serial")
- public class MailSendEvent extends ApplicationContextEvent{
- private String to ;
-
- public MailSendEvent(ApplicationContext source, String to) {
- super(source);
- this.to = to ;
- }
-
- public String getTo() {
- return this.to ;
- }
-
- }
- package com.baobaotao.event;
-
- import org.springframework.context.ApplicationListener;
-
- public class MailSendListener implements ApplicationListener<MailSendEvent>{
-
- public void onApplicationEvent(MailSendEvent event) {
- MailSendEvent mse = (MailSendEvent)event ;
- System.out.println("MailSendListener:向" + mse.getTo() + "发送完一封邮件");
- }
-
- }
- package com.baobaotao.event;
-
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
-
- public class MailSender implements ApplicationContextAware{
- private ApplicationContext ctx ;
-
- public void setApplicationContext(ApplicationContext ctx)
- throws BeansException {
- this.ctx = ctx ;
- }
-
- public void sendMail(String to) {
- System.out.println("MailSender:模拟发送邮件...");
- MailSendEvent mse = new MailSendEvent(this.ctx, to) ;
- ctx.publishEvent(mse) ;
- }
-
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:p="http://www.springframework.org/schema/p"
- 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
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean class="com.baobaotao.event.MailSendListener" />
- <bean id="mailSender" class="com.baobaotao.event.MailSender" />
- </beans>
- package com.baobaotao.event;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class TestSendMail {
- public static void main(String[] args) {
- ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml") ;
- MailSender mailSender = (MailSender)ctx.getBean("mailSender") ;
- mailSender.sendMail("449261417@qq.com") ;
- }
- }
输出结果为:MailSender:模拟发送邮件...
MailSendListener:向449261417@qq.com发送完一封邮件