分享

Spring常用的接口和类

 爱学习_守之 2015-03-12
参见:http://chenjumin./blog/355544
参见:http://chenjumin./blog/364904
参见:http://chenjumin./blog/996389

一、ApplicationContextAware接口
当一个类需要获取ApplicationContext实例时,可以让该类实现ApplicationContextAware接口。代码展示如下:
  1. public class Animal implements ApplicationContextAware, BeanNameAware{  
  2.     private String beanName;  
  3.     private ApplicationContext applicationContext;  
  4.   
  5.     public void setBeanName(String name) {  
  6.         this.beanName = name;  
  7.     }  
  8.       
  9.     /** 
  10.      * @param applicationContext 该参数将由Spring容器自动赋值 
  11.      */  
  12.     public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {  
  13.         this.applicationContext = applicationContext;  
  14.     }  
  15.   
  16.     public void run(){  
  17.         System.out.println(beanName);  
  18.           
  19.         //发布自定义事件  
  20.         AnimalEvent event = new AnimalEvent(this"老虎");  
  21.         applicationContext.publishEvent(event);  
  22.     }  
  23. }
通过@Autowired注解可以自动装配一些常用对象实例:
  1. @Autowired  
  2. private MessageSource messageSource;   
  3.   
  4. @Autowired  
  5. private ResourceLoader resourceLoader;   
  6.   
  7. @Autowired  
  8. private ApplicationContext applicationContext;

二、ApplicationEvent抽象类
当需要创建自定义事件时,可以新建一个继承自ApplicationEvent抽象类的类。代码展示如下:
  1. /** 
  2.  * 自定义事件 
  3.  */  
  4. public class AnimalEvent extends ApplicationEvent {  
  5.     private String name;  
  6.       
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.   
  11.     /** 
  12.      * @param source 事件源对象 
  13.      */  
  14.     public AnimalEvent(Object source){  
  15.         super(source);  
  16.     }  
  17.       
  18.     public AnimalEvent(Object source, String name){  
  19.         super(source);  
  20.         this.name = name;  
  21.     }  


三、ApplicationListener接口
当需要监听自定义事件时,可以新建一个实现ApplicationListener接口的类,并将该类配置到Spring容器中。代码展示如下:
  1. /** 
  2.  * 自定义事件监听器 
  3.  */  
  4. public class CustomEventListener implements ApplicationListener {  
  5.     public void onApplicationEvent(ApplicationEvent event) {  
  6.         if(event instanceof AnimalEvent){  
  7.             AnimalEvent animalEvent = (AnimalEvent)event;  
  8.             System.out.println("触发自定义事件:Animal name is " + animalEvent.getName());  
  9.         }  
  10.     }  


  1. <!-- 自定义事件监听器:Spring容器自动注册它 -->  
  2. <bean id="customEventListener" class="com.cjm.spring.CustomEventListener"/>  
要发布自定义事件,需要调用ApplicationContext的publishEvent方法,具体用法请看Animal类的源码。

四、BeanNameAware接口
当bean需要获取自身在容器中的id/name时,可以实现BeanNameAware接口。

五、InitializingBean接口
当需要在bean的全部属性设置成功后做些特殊的处理,可以让该bean实现InitializingBean接口。效果等同于bean的init-method属性的使用或者@PostContsuct注解的使用。
三种方式的执行顺序:先注解,然后执行InitializingBean接口中定义的方法,最后执行init-method属性指定的方法。

六、DisposableBean接口
当需要在bean销毁之前做些特殊的处理,可以让该bean实现DisposableBean接口。效果等同于bean的destroy-method属性的使用或者@PreDestory注解的使用。
三种方式的执行顺序:先注解,然后执行DisposableBean接口中定义的方法,最后执行destroy-method属性指定的方法。

七、BeanPostProcessor接口
当需要对受管bean进行预处理时,可以新建一个实现BeanPostProcessor接口的类,并将该类配置到Spring容器中。
实现BeanPostProcessor接口时,需要实现以下两个方法“
postProcessBeforeInitialization在受管bean的初始化动作之前调用
postProcessAfterInitialization在受管bean的初始化动作之后调用
容器中的每个Bean在创建时都会恰当地调用它们。代码展示如下:
  1. public class CustomBeanPostProcessor implements BeanPostProcessor {  
  2.     /** 
  3.      * 初始化之前的回调方法 
  4.      */  
  5.     public Object postProcessBeforeInitialization(Object bean, String beanName)throws BeansException {  
  6.         System.out.println("postProcessBeforeInitialization: " + beanName);  
  7.         return bean;  
  8.     }  
  9.   
  10.     /** 
  11.      * 初始化之后的回调方法 
  12.      */  
  13.     public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {  
  14.         System.out.println("postProcessAfterInitialization: " + beanName);  
  15.         return bean;  
  16.     }  


  1. <!-- 自定义受管Bean的预处理器:Spring容器自动注册它 -->  
  2. <bean id="customBeanPostProcessor" class="com.cjm.spring.CustomBeanPostProcessor"/> 

八、BeanFactoryPostProcessor接口
当需要对Bean工厂进行预处理时,可以新建一个实现BeanFactoryPostProcessor接口的类,并将该类配置到Spring容器中。代码展示如下:
  1. public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {  
  2.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {  
  3.         System.out.println(beanFactory.getClass().getSimpleName());  
  4.     }  
  5. }

  1. <!-- 自定义Bean工厂的预处理器:Spring容器自动注册它 -->  
  2. <bean id="customBeanFactoryPostProcessor" class="com.cjm.spring.CustomBeanFactoryPostProcessor"/>  

Spring内置的实现类:
1、PropertyPlaceholderConfigurer类
用于读取Java属性文件中的属性,然后插入到BeanFactory的定义中。
  1. <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  2.     <property name="locations">  
  3.         <list>  
  4.             <value>jdbc.properties</value>  
  5.         </list>  
  6.     </property>  
  7. </bean>  
  8.   
  9. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  10.     <property name="driverClassName"><value>${jdbc.driverClassName}</value></property>  
  11.     <property name="url"><value>${jdbc.url}</value></property>  
  12.     <property name="username"><value>${jdbc.username}</value></property>  
  13.     <property name="password"><value>${jdbc.password}</value></property>  
  14. </bean>  
PropertyPlaceholderConfigurer的另一种精简配置方式(context命名空间):
  1. <context:property-placeholder location="classpath:jdbc.properties, classpath:mails.properties"/>  
Java属性文件内容:
                   jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
                   jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
                   jdbc.username=qycd
                   jdbc.password=qycd
除了可以读取Java属性文件中的属性外,还可以读取系统属性和系统环境变量的值。
读取系统环境变量的值:${JAVA_HOME}
                 读取系统属性的值:${user.dir}

2、PropertyOverrideConfigurer类
用于读取Java属性文件中的属性,并覆盖XML配置文件中的定义,即PropertyOverrideConfigurer允许XML配置文件中有默认的配置信息。
Java属性文件的格式:

                      beanName.property=value

                      beanName是属性占位符企图覆盖的bean名,property是企图覆盖的数姓名。

  1. <bean id="propertyOverrideConfigurer" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">  
  2.     <property name="locations">  
  3.         <list>  
  4.             <value>jdbc.properties</value>  
  5.         </list>  
  6.     </property>  
  7. </bean>  
  8.   
  9. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  10.     <property name="driverClassName" value="11"/>  
  11.     <property name="url" value="22"/>  
  12.     <property name="username" value="33"/>  
  13.     <property name="password" value="44"/>  
  14. </bean> 
Java属性文件内容:
                dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
                dataSource.url=jdbc:oracle:thin:@localhost:1521:orcl
                dataSource.username=qycd
                dataSource.password=qycd

九、ResourceBundleMessageSource类
提供国际化支持,bean的名字必须为messageSource。此处,必须存在一个名为jdbc的属性文件。
  1. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  2.     <property name="basenames">  
  3.         <list>  
  4.             <value>jdbc</value>  
  5.         </list>  
  6.     </property>  
  7. </bean> 
jdbc.properties属性文件的内容:
  1. welcome={0}, welcome to guangzhou!  
  1. AbstractApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");  
  2.   
  3. ctx.getMessage("welcome"new String[]{"张三"}, "", Locale.CHINA); 

十、FactorBean接口
用于创建特定的对象,对象的类型由getObject方法的返回值决定。
  1. public class MappingFactoryBean implements FactoryBean {  
  2.     /** 
  3.      * 获取mapping配置对象 
  4.      * @return mapping配置 
  5.      */  
  6.     public Object getObject() throws Exception {  
  7.         List<String> configs = ApplicationContext.getContext().getApplication().getMappingConfigs();  
  8.         return configs.toArray(new String[configs.size()]);  
  9.     }  
  10.   
  11.     /** 
  12.      * 返回Bean的类型 
  13.      * @return Bean的类型 
  14.      */  
  15.     public Class<?> getObjectType() {  
  16.         return String[].class;  
  17.     }  
  18.   
  19.     /** 
  20.      * 返回Bean是否是单例的 
  21.      * @return true表示是单例的 
  22.      */  
  23.     public boolean isSingleton() {  
  24.         return true;  
  25.     }  
  26. }  

  1. public class MappingAutowiring implements BeanPostProcessor {  
  2.     /** 
  3.      * 映射配置 
  4.      */  
  5.     private String[] mappingResources;  
  6.   
  7.     /** 
  8.      * 获取映射配置信息 
  9.      * @return 映射配置 
  10.      */  
  11.     public String[] getMappingResources() {  
  12.         return mappingResources;  
  13.     }  
  14.   
  15.     /** 
  16.      * 设置映射配置信息 
  17.      * @param mappingResources 映射配置 
  18.      */  
  19.     public void setMappingResources(String[] mappingResources) {  
  20.         this.mappingResources = mappingResources;  
  21.     }  
  22.   
  23.     /** 
  24.      * 自动装配 
  25.      * @param bean Spring容器托管的bean 
  26.      * @param beanName Bean名称 
  27.      * @return 装配了映射文件后的对象 
  28.      */  
  29.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  30.         if (bean instanceof LocalSessionFactoryBean) {  
  31.             ((LocalSessionFactoryBean) bean).setMappingResources(mappingResources);  
  32.         }  
  33.         return bean;  
  34.     }  
  35.   
  36.     public Object postProcessAfterInitialization(Object bean, String beanName)  
  37.             throws BeansException {  
  38.         return bean;  
  39.     }  
  40. }  

  1. <bean id="mappingAutowiring" class="com.achievo.framework.server.core.deploy.MappingAutowiring">  
  2.     <property name="mappingResources" ref="mappingResources" />  
  3. </bean>  
  4.   
  5. <bean id="mappingResources" class="com.achievo.framework.server.core.deploy.MappingFactoryBean" />  

十一、CustomEditorConfigurer类
可以读取实现java.beans.PropertyEditor接口的类,将字符串转为指定的类型。更方便的可以使用PropertyEditorSupport。PropertyEditorSupport实现PropertyEditor接口,必须重新定义setAsText。
  1. public class Hello {  
  2.     private String message;  
  3.     private User user;  
  4.       
  5.     public String getMessage() {  
  6.         return message;  
  7.     }  
  8.     public void setMessage(String message) {  
  9.         this.message = message;  
  10.     }  
  11.     public User getUser() {  
  12.         return user;  
  13.     }  
  14.     public void setUser(User user) {  
  15.         this.user = user;  
  16.     }  

自定义属性编辑器继承PropertyEditorSupport类,重写setAsText方法。
  1. public class UserEditor extends PropertyEditorSupport{  
  2.     @Override  
  3.     public void setAsText(String text) throws IllegalArgumentException {  
  4.         //类型为User的变量声明了自定义属性编辑器,其值规定为逗号分割的字符串  
  5.         String[] arr = text.split(",");  
  6.         Integer age = new Integer(arr[1]);  
  7.           
  8.         User user = new User();  
  9.         user.setName(arr[0]);  
  10.         user.setAge(age);  
  11.           
  12.         setValue(user);  
  13.     }  
  14. }  
bean配置
  1. <bean id="configBean"   
  2. class="org.springframework.beans.factory.config.CustomEditorConfigurer">   
  3.     <property name="customEditors">  
  4.         <map>  
  5.             <!-- 类型为User的变量都通过UserEditor间接设值 -->  
  6.             <entry key="User">  
  7.                 <bean id="userEditor" class="UserEditor"/>  
  8.             </entry>  
  9.         </map>     
  10.     </property>  
  11. </bean>   
  12.   
  13. <bean id="hello" class="Hello">   
  14.     <property name="message" value="hello" />   
  15.     <property name="user" value="chenjumin,20"/><!-- 类型为User的变量声明了自定义属性编辑器,其值规定为逗号分割的字符串 -->   
  16. </bean>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多