`
celeskyking
  • 浏览: 25237 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

通过Spring实现对自定义注解属性进行资源注入

阅读更多

通过上一篇 利用自定义Java注解实现资源注入 介绍的方法,我们实现了通过自定义注解完成了对DataSource资源的注入,但在实际应用中,我们通常不希望去显式的去声明这样的MyAnnotationBeanProcessor对象来帮助我们完成注入,而是希望通过Spring帮我们“悄悄地”完成。
继 利用自定义Java注解实现资源注入 里的代码(部分代码)不变,我们希望在测试类中以如下方法调用便可以实现资源的注入:


    import org.springframework.context.support.ClassPathXmlApplicationContext; 
    
    import com.annotation.MyService; 
    
    public class SpringWiringTest { 
        public static void main(String args[]) { 
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/spring/applicationContext.xml"); 
            MyService b = (MyService)ctx.getBean("myService"); // 通过Spring去管理bean,此时已完成了对标有DataSource注解的资源的注入 
            System.out.println(b.selectForObjectFromB("", null)); 
            System.out.println(b.selectForObjectFromA("", null)); 
        } 
    }


注:MyService类实现在 利用自定义Java注解实现资源注入 中。

为了实现上面的目标,我们就不能使用MyAnnotationBeanProcessor.java类来实现对资源的注入了,我们必须实现一个能融入Spring的BeanProcessor类才行。
DataSourceBeanProcessor.java类实现BeanPostProcessor、PriorityOrdered接口:


    import java.lang.reflect.Field; 
    
    import org.springframework.beans.BeansException; 
    import org.springframework.beans.factory.config.BeanPostProcessor; 
    import org.springframework.core.Ordered; 
    import org.springframework.core.PriorityOrdered; 
    
    public class DataSourceBeanProcessor implements BeanPostProcessor, PriorityOrdered { 
        @Override
        // 在这里完成资源注入 
        public Object postProcessAfterInitialization(Object bean, String beanName) 
            throws BeansException { 
            Class<?> cls = bean.getClass(); 
            for (Field field : cls.getDeclaredFields()) { 
                if (field.isAnnotationPresent(DataSource.class)) { 
                    DataSourceStaticWiring.wiring(bean, field); 
                } 
            } 
            return bean; 
        } 
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) 
            throws BeansException { 
            return bean; 
        } 
    
        @Override
        public int getOrder() { 
            return Ordered.LOWEST_PRECEDENCE; 
        } 
    }


下面来看DataSourceStaticWiring的实现,与前一篇 里的DataSourceWiring.java类相比,改动点有以下三个:
1.不需要实现IFieldWiring接口
2.删除annotationClass方法
3.将wiring方法修改为static方法
具体代码如下:


    import java.lang.reflect.Field; 
    
    public class DataSourceStaticWiring { 
    
        public static void wiring(Object object, Field field) { 
            Object fieldObj = ReflectUtils.getFieldValue(object, field.getName()); 
            if (fieldObj != null) { 
                return; 
            } 
            DataSource annotation = field.getAnnotation(DataSource.class); 
            String type = annotation.type(); 
            String sqlMap = annotation.sqlMap(); 
            // 这里可以用缓存来实现,不用每次都去创建新的SqlMapClient对象 
            SqlMapClient sqlMapImpl = new SqlMapClient(sqlMap, type); 
            ReflectUtils.setFieldValue(object, field.getName(), SqlMapClient.class, sqlMapImpl); 
        } 
    }


注:SqlMapClient、ReflectUtils实现在上一篇 利用自定义Java注解实现资源注入 中。

代码已准备就绪,接下来是配置Spring:applicationContext.xml


    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
                            http://www.springframework.org/schema/aop  
                            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
                            http://www.springframework.org/schema/tx  
                            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
                            http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-2.5.xsd" 
        default-lazy-init="true">
         
        <!-- 自定义的BeanProcessor -->
        <bean class="com.annotation.DataSourceBeanProcessor" />
        <context:component-scan base-package="com.annotation" />
    
        <!-- 测试用bean -->
        <bean id="myService" class="com.annotation.MyService" destroy-method="close">
        </bean>
    </beans>


测试代码其实已经在前面列出来了。SpringWiringTest.java


    import org.springframework.context.support.ClassPathXmlApplicationContext; 
    
    import com.annotation.MyService; 
    
    public class SpringWiringTest { 
        public static void main(String args[]) { 
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/spring/applicationContext.xml"); 
            MyService b = (MyService)ctx.getBean("myService"); 
            System.out.println(b.selectForObjectFromB("", null)); 
            System.out.println(b.selectForObjectFromA("", null)); 
        } 
    }


执行结果:

SqlMapClient[sqlMap=com/annotation/sql-map-config-B.xml,type=B]
SqlMapClient[sqlMap=com/annotation/sql-map-config-A.xml,type=A]


由结果可见,我们利用Spring完成了对DataSource资源的注入了。

在这里如果还想扩展的话,就需要新建类假设为InParamBeanProcessor,实现BeanPostProcessor、PriorityOrdered接口,然后实现其中的方法,对资源进行注入,这里就是扩展Spring了,与本篇介绍的方法相同。

注:以上代码重在演示,其实这个需求可以在Spring中管理两个不同的SqlMapClient对象,然后通过Spring的自动注入实现。
分享到:
评论

相关推荐

    Spring注解注入属性

    Spring注解注入属性

    Spring 自定义注解注入properties文件的值jar包

    Spring 自定义注解注入properties文件的值jar包,下面为使用方法 在xml配置文件中,这样加载properties文件 ...

    ssh2框架整合,struts2和hibernate均交由spring管理,用注解的方式由spring注入

    ssh2框架整合,struts2和hibernate均交由spring管理,用注解的方式由spring注入

    DynamicConfigRefresh:依赖Spring自定义注解完成配置文件注入和更改配置文件动态更新数据功能

    DynamicConfigRefresh:依赖Spring自定义注解完成配置文件注入和更改配置文件动态更新数据功能

    spring为类的静态属性实现注入实例方法

    在本篇文章里小编给大家整理的是关于spring为类的静态属性实现注入实例方法,有需要的朋友们可以参考下。

    Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法

    今天小编就为大家分享一篇关于Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

    Spring启动后获取所有拥有特定注解的Bean实例代码

    主要介绍了Spring启动后获取所有拥有特定注解的Bean实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下

    spring.net中文手册在线版

    使用对象或类的属性值进行注入 4.3.5.2.使用字段值进行注入 4.3.5.3.使用方法的返回值进行注入 4.3.6.IFactoryObject接口的其它实现 4.3.6.1.Log4Net 4.3.7.使用depends-on 4.3.8.自动装配协作对象 4.3.9.检查依赖项...

    从零开始学Spring Boot

    1.19 Spring Boot使用Druid(编程注入) 1.20 Spring Boot普通类调用bean 1.21 使用模板(thymeleaf-freemarker) 1.22 Spring Boot 添加JSP支持 1.23 Spring Boot Servlet 1.24 Spring Boot过滤器、监听器 1.25 ...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring.3.x企业应用开发实战(完整版).part2

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    Spring 2.0 开发参考手册

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. ...

    Spring攻略(第二版 中文高清版).part2

    10.4 通过BlazeDS/Spring暴露服务 411 10.4.1 问题 411 10.4.2 解决方案 411 10.4.3 工作原理 411 10.5 使用服务器端对象 418 10.5.1 问题 418 10.5.2 解决方案 418 10.5.3 工作原理 418 10.6 使用...

    IoC容器的设计(利用反射、注解和工厂模式实现)

    3.自定义两个业务类Group和User,创建一个测试类Test,对IoC容器进行测试; 实验思路: 我们需要将自定义四个注解,然后将Group和User类使用@Component注解,在User类中创建Group类的实例化对象并设置为自动装配,...

    spring chm文档

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. ...

    Spring3.x企业应用开发实战(完整版) part1

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    springboot学习思维笔记.xmind

    通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter中 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器...

    springboot通过@Condition注解类型完成加载配置内容

    通过@Bean和@Condition 注解自定义对于的condition里面根据自定义的条件实现指定类注入到spring中;@ConditionalOnProperty可以根据配置文件中的 属性值不同将不同的类注入到spring中 该资源中案例完整,代码简单移动

Global site tag (gtag.js) - Google Analytics