ITeye博客

不重复配置——利用Spring通用化配置

a52071453 · 2012-10-17 09:40 · spring mvc · spring · 编程语言 · Spring · Bean · Markdown

还记得 如下这种配置吗:

 

1、struts2作用域:每一个Action我们必须设置scope为prototype   每次都做重复的配置,而且有时候忘记配置还会出现bug,想不想删掉它?

 

<bean id="**Action" class="***Action" scope="prototype">

 

2、在使用spring集成hibernate时,每次都必须注入sessionFactory,虽然可以用父子bean解决 但还是要写parent="abstractHibernateDao"之类的。

<bean id="***Dao" class="***DaoImpl">

    <property name="sessionFactory" ref="sessionFactory">

</bean>

 

受够了这种配置,得想法解决这个重复配置,怎么解决呢?

 

思路:

在BeanFactory创建Bean之前查找所有我们需要通用化配置的Bean 然后修改BeanDefinition注入我们的通用数据就可以解决我们这个问题。

 

Spring提供了BeanFactoryPostProcessor扩展点,用于提供给我们修改BeanDefinition数据的。

 

还记得org.springframework.beans.factory.config.PropertyPlaceholderConfigurer吗? 替换占位符数据,它就是一个BeanFactoryPostProcessor的实现。

 

好了思路有了,接下来我们实现一下吧:

1、XML配置方式

 

 * 

 * 使用方法:<br/>

 * <pre>

 *  <bean class="cn.javass.common.spring.CommonConfigureProcessor">

       <property name="config">

            <map>

               <!--  aspectj表达式 选择所有Action结尾的Bean 注入scope数据 为 prototype  -->

               <entry key="cn.javass..*Action">

                   <props>

                       <prop key="scope">prototype</prop>

                   </props>

               </entry>

               <!-- aspectj表达式 选择所有的HibernateDaoSupport实现Bean 注入sessionFactory -->

               <entry key="org.springframework.orm.hibernate3.support.HibernateDaoSupport+">

                  <props>

                     <prop key="property-ref">sessionFactory=sessionFactory</prop>

                  </props>

               </entry>

            </map>          

       </property>

   </bean>

 * </pre>

 * 

 * 目前支持三种配置:

 *  scope:注入作用域

 *  property-ref:注入Bean引用 如之上的sessionFactory

 *     propertyName=beanName

 *  property-value:注入常量值

 *     propertyName=常量

 

2、CommonConfigureProcessor源码

 

Java代码 复制代码 收藏代码

  1. package cn.javass.common.spring;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Map.Entry;
  7. import java.util.Properties;
  8. import org.aspectj.bridge.IMessageHandler;
  9. import org.aspectj.weaver.ResolvedType;
  10. import org.aspectj.weaver.World;
  11. import org.aspectj.weaver.bcel.BcelWorld;
  12. import org.aspectj.weaver.patterns.Bindings;
  13. import org.aspectj.weaver.patterns.FormalBinding;
  14. import org.aspectj.weaver.patterns.IScope;
  15. import org.aspectj.weaver.patterns.PatternParser;
  16. import org.aspectj.weaver.patterns.SimpleScope;
  17. import org.aspectj.weaver.patterns.TypePattern;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import org.springframework.beans.BeansException;
  21. import org.springframework.beans.factory.config.BeanDefinition;
  22. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  23. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  24. import org.springframework.beans.factory.config.RuntimeBeanNameReference;
  25. import org.springframework.beans.factory.config.RuntimeBeanReference;
  26. import org.springframework.util.StringUtils;
  27. /**
  28. *
  29. * 设置通用配置<br/>
  30. *
  31. * 使用方法:<br/>
  32. * <pre>
  33. *  <bean class="cn.javass.common.spring.CommonConfigureProcessor">
  34. <property name="config">
  35. <map>
  36. <!--  aspectj表达式 选择所有Action结尾的Bean 注入scope数据 为 prototype  -->
  37. <entry key="cn.javass..*Action">
  38. <props>
  39. <prop key="scope">prototype</prop>
  40. </props>
  41. </entry>
  42. <!-- aspectj表达式 选择所有的HibernateDaoSupport实现Bean 注入sessionFactory -->
  43. <entry key="org.springframework.orm.hibernate3.support.HibernateDaoSupport+">
  44. <props>
  45. <prop key="property-ref">sessionFactory=sessionFactory</prop>
  46. </props>
  47. </entry>
  48. </map>
  49. </property>
  50. </bean>
  51. * </pre>
  52. *
  53. * 目前支持三种配置:
  54. *  scope:注入作用域
  55. *  property-ref:注入Bean引用 如之上的sessionFactory
  56. *     propertyName=beanName
  57. *  property-value:注入常量值
  58. *     propertyName=常量
  59. *
  60. * @author Zhangkaitao
  61. * @version 1.0
  62. *
  63. */
  64. public class CommonConfigureProcessor implements BeanFactoryPostProcessor {
  65. private Logger log = LoggerFactory.getLogger(CommonConfigureProcessor.class);
  66. private Map<String, Properties> config = new HashMap<String, Properties>();
  67. public void setConfig(Map<String, Properties> config) {
  68. this.config = config;
  69. }
  70. @Override
  71. public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
  72. log.debug("apply common config start");
  73. for(Entry<String, Properties> entry : config.entrySet()) {
  74. String aspectjPattern = entry.getKey();
  75. Properties props = entry.getValue();
  76. List<BeanDefinition> bdList = findBeanDefinition(aspectjPattern, factory);
  77. apply(bdList, props);
  78. }
  79. log.debug("apply common config end");
  80. }
  81. private void apply(List<BeanDefinition> bdList, Properties props) {
  82. for(Entry<Object, Object> entry : props.entrySet()) {
  83. String key = (String) entry.getKey();
  84. String value = (String) entry.getValue();
  85. switch(SupportedConfig.keyToEnum(key)) {
  86. case scope :
  87. applyScope(bdList, value);
  88. break;
  89. case propertyRef:
  90. applyPropertyRef(bdList, value);
  91. break;
  92. case propertyValue:
  93. applyPropertyValue(bdList, value);
  94. break;
  95. default:
  96. throw new IllegalArgumentException(String.format("错误的配置:[%s]", key));
  97. }
  98. }
  99. }
  100. private void applyPropertyValue(List<BeanDefinition> bdList, String value) {
  101. for(BeanDefinition bd : bdList) {
  102. String propertyName = value.split("=")[0];
  103. String propertyValue = value.substring(propertyName.length()+1);
  104. bd.getPropertyValues().add(propertyName, propertyValue);
  105. log.debug("apply property value {} to {}", value, bd.getBeanClassName());
  106. }
  107. }
  108. private void applyPropertyRef(List<BeanDefinition> bdList, String value) {
  109. for(BeanDefinition bd : bdList) {
  110. String propertyName = value.split("=")[0];
  111. String propertyValue = value.substring(propertyName.length()+1);
  112. bd.getPropertyValues().addPropertyValue(propertyName, new RuntimeBeanReference(propertyValue));
  113. log.debug("apply property ref {} to {}", value, bd.getBeanClassName());
  114. }
  115. }
  116. private void applyScope(List<BeanDefinition> bdList, String value) {
  117. for(BeanDefinition bd : bdList) {
  118. bd.setScope(value);
  119. log.debug("apply scope {} to {}", value, bd.getBeanClassName());
  120. }
  121. }
  122. private List<BeanDefinition> findBeanDefinition(String aspectjPattern, ConfigurableListableBeanFactory factory) {
  123. List<BeanDefinition> bdList = new ArrayList<BeanDefinition>();
  124. for(String beanName : factory.getBeanDefinitionNames()) {
  125. BeanDefinition bd = factory.getBeanDefinition(beanName);
  126. if(matches(aspectjPattern, bd.getBeanClassName())) {
  127. bdList.add(bd);
  128. }
  129. }
  130. return bdList;
  131. }
  132. private boolean matches(String aspectjPattern, String beanClassName) {
  133. if(!StringUtils.hasLength(beanClassName)) {
  134. return false;
  135. }
  136. return new AspectJTypeMatcher(aspectjPattern).matches(beanClassName);
  137. }
  138. //支持的操作
  139. private static enum SupportedConfig {
  140. scope("scope"),
  141. propertyRef("property-ref"),
  142. propertyValue("property-value"),
  143. error("error"); //出错的情况
  144. private final String key;
  145. private SupportedConfig(String key) {
  146. this.key = key;
  147. }
  148. public static SupportedConfig keyToEnum(String key) {
  149. if(key == null) {
  150. return error;
  151. }
  152. for(SupportedConfig config : SupportedConfig.values()) {
  153. if(config.key.equals(key.trim())) {
  154. return config;
  155. }
  156. }
  157. return error;
  158. }
  159. }
  160. public static interface TypeMatcher {
  161. public boolean matches(String className);
  162. }
  163. static class AspectJTypeMatcher implements TypeMatcher {
  164. private final World world;
  165. private final TypePattern typePattern;
  166. public AspectJTypeMatcher(String pattern) {
  167. this.world = new BcelWorld(Thread.currentThread().getContextClassLoader(), IMessageHandler.THROW, null);
  168. this.world.setBehaveInJava5Way(true);
  169. PatternParser patternParser = new PatternParser(pattern);
  170. TypePattern typePattern = patternParser.parseTypePattern();
  171. typePattern.resolve(this.world);
  172. IScope scope = new SimpleScope(this.world, new FormalBinding[0]);
  173. this.typePattern = typePattern.resolveBindings(scope, Bindings.NONE, false, false);
  174. }
  175. @Override
  176. public boolean matches(String className) {
  177. ResolvedType resolvedType = this.world.resolve(className);
  178. return this.typePattern.matchesStatically(resolvedType);
  179. }
  180. }
  181. public static void main(String[] args) {
  182. //System.out.println(new AspectJTypeMatcher("cn.javass..*Action").matches("cn.javass.test.web.action.AbcAction"));
  183. //System.out.println(new AspectJTypeMatcher("com.opensymphony.xwork2.ActionSupport+").matches("cn.javass.erp.web.action.MoneyAction"));
  184. }
  185. }
package cn.javass.common.spring;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.patterns.Bindings;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.TypePattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.util.StringUtils;
/**
 * 
 * 设置通用配置<br/>
 * 
 * 使用方法:<br/>
 * <pre>
 *  <bean class="cn.javass.common.spring.CommonConfigureProcessor">
       <property name="config">
            <map>
               <!--  aspectj表达式 选择所有Action结尾的Bean 注入scope数据 为 prototype  -->
               <entry key="cn.javass..*Action">
                   <props>
                       <prop key="scope">prototype</prop>
                   </props>
               </entry>
               <!-- aspectj表达式 选择所有的HibernateDaoSupport实现Bean 注入sessionFactory -->
               <entry key="org.springframework.orm.hibernate3.support.HibernateDaoSupport+">
                  <props>
                     <prop key="property-ref">sessionFactory=sessionFactory</prop>
                  </props>
               </entry>
            </map>          
       </property>
   </bean>
 * </pre>
 * 
 * 目前支持三种配置:
 *  scope:注入作用域
 *  property-ref:注入Bean引用 如之上的sessionFactory
 *     propertyName=beanName
 *  property-value:注入常量值
 *     propertyName=常量
 * 
 * @author Zhangkaitao
 * @version 1.0
 *
 */
public class CommonConfigureProcessor implements BeanFactoryPostProcessor {
    
    private Logger log = LoggerFactory.getLogger(CommonConfigureProcessor.class);

    private Map<String, Properties> config = new HashMap<String, Properties>();
    public void setConfig(Map<String, Properties> config) {
        this.config = config;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
        log.debug("apply common config start");
        for(Entry<String, Properties> entry : config.entrySet()) {
            String aspectjPattern = entry.getKey();
            Properties props = entry.getValue();

            List<BeanDefinition> bdList = findBeanDefinition(aspectjPattern, factory);
            
            apply(bdList, props);
        }
        log.debug("apply common config end");
    }


    private void apply(List<BeanDefinition> bdList, Properties props) {
        for(Entry<Object, Object> entry : props.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            
            switch(SupportedConfig.keyToEnum(key)) {
                case scope : 
                    applyScope(bdList, value);
                    break;
                case propertyRef:
                    applyPropertyRef(bdList, value);
                    break;
                case propertyValue:
                    applyPropertyValue(bdList, value);
                    break;
                default:
                    throw new IllegalArgumentException(String.format("错误的配置:[%s]", key));
            }
            
            
        }
    }


    private void applyPropertyValue(List<BeanDefinition> bdList, String value) {
        for(BeanDefinition bd : bdList) {
            
            String propertyName = value.split("=")[0]; 
            String propertyValue = value.substring(propertyName.length()+1);
            bd.getPropertyValues().add(propertyName, propertyValue);
            
            log.debug("apply property value {} to {}", value, bd.getBeanClassName());
        }
    }

    private void applyPropertyRef(List<BeanDefinition> bdList, String value) {
        for(BeanDefinition bd : bdList) {
            
            String propertyName = value.split("=")[0]; 
            String propertyValue = value.substring(propertyName.length()+1);
            bd.getPropertyValues().addPropertyValue(propertyName, new RuntimeBeanReference(propertyValue));
            
            log.debug("apply property ref {} to {}", value, bd.getBeanClassName());
        }
    }

    private void applyScope(List<BeanDefinition> bdList, String value) {
        for(BeanDefinition bd : bdList) {
            bd.setScope(value);
            log.debug("apply scope {} to {}", value, bd.getBeanClassName());
        }
    }

    private List<BeanDefinition> findBeanDefinition(String aspectjPattern, ConfigurableListableBeanFactory factory) {
        List<BeanDefinition> bdList = new ArrayList<BeanDefinition>();
        
        for(String beanName : factory.getBeanDefinitionNames()) {
            BeanDefinition bd = factory.getBeanDefinition(beanName);
            
            if(matches(aspectjPattern, bd.getBeanClassName())) {
                bdList.add(bd);
            }
            
        }
        
        return bdList;
    }

    
    private boolean matches(String aspectjPattern, String beanClassName) {
        if(!StringUtils.hasLength(beanClassName)) {
            return false;
        }
        return new AspectJTypeMatcher(aspectjPattern).matches(beanClassName);
    }
    
    //支持的操作
    private static enum SupportedConfig {
        scope("scope"), 
        propertyRef("property-ref"),
        propertyValue("property-value"),
        
        error("error"); //出错的情况

        private final String key;
        private SupportedConfig(String key) {
            this.key = key;
        }
        
        public static SupportedConfig keyToEnum(String key) {
            if(key == null) {
                return error;
            }
            for(SupportedConfig config : SupportedConfig.values()) {
                if(config.key.equals(key.trim())) {
                    return config;
                }
            }
            return error;
        }
        
    }
    
    
    public static interface TypeMatcher {
        public boolean matches(String className);
    }
    
    static class AspectJTypeMatcher implements TypeMatcher {
        private final World world;
        private final TypePattern typePattern;
        
        public AspectJTypeMatcher(String pattern) {
         
            this.world = new BcelWorld(Thread.currentThread().getContextClassLoader(), IMessageHandler.THROW, null);
            this.world.setBehaveInJava5Way(true);
            PatternParser patternParser = new PatternParser(pattern);
            TypePattern typePattern = patternParser.parseTypePattern();
            typePattern.resolve(this.world);
            IScope scope = new SimpleScope(this.world, new FormalBinding[0]);
            this.typePattern = typePattern.resolveBindings(scope, Bindings.NONE, false, false);
        }
        @Override
        public boolean matches(String className) {
            ResolvedType resolvedType = this.world.resolve(className);
            return this.typePattern.matchesStatically(resolvedType);
        }
    }
    
    public static void main(String[] args) {
        //System.out.println(new AspectJTypeMatcher("cn.javass..*Action").matches("cn.javass.test.web.action.AbcAction"));
        //System.out.println(new AspectJTypeMatcher("com.opensymphony.xwork2.ActionSupport+").matches("cn.javass.erp.web.action.MoneyAction"));
    }
}

 

此类只实现基本的通用配置,欢迎大家提供想法并完善这个工具类。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。