zoukankan      html  css  js  c++  java
  • Spring AOP:@DeclareParents 为对象添加方法

    通过@Before @After @Around都注解,我们为对象原有的方法添加上了新的功能。那么,我们能不能为对象添加新的方法呢?通过 @DeclareParents  ,答案是肯定的。

    定义一个 Person 的空类及其子类 Student

    @Component
    public class Person {
    }
    
    
    @Component
    public class Student extends Person {
        public void sayIdentification(){
            System.out.println("我是学生。");
        }
    }

    定义一个名为 Skill 的接口及它的实现类 SkillImpl。我们将要把 SkillImpl 的getSkill()方法添加到其他的类实例

    @Component
    public interface Skill {
        void getSkill(String skill);
    }
    
    @Component
    public class SkillImpl implements Skill { @Override public void getSkill(String skill) { System.out.println(skill); } }

    SpringAop 配置类

    @Component
    @Aspect
    public class AopConfig {
    
        // “...aop.Person”后面的 “+” 号,表示只要是Person及其子类都可以添加新的方法
        @DeclareParents(value = "com.san.spring.aop.Person+", defaultImpl = SkillImpl.class)
        public Skill skill;
    }

    SpringConfig 配置类

    @ComponentScan
    @Configuration
    @EnableAspectJAutoProxy
    public class SpringConfig {
    }

    Test

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfig.class)
    public class AopTest {
    
        @Autowired
        private Student student;
    
        @Test
        public void test(){
            Skill skill = (Skill)student; // 通过类型转换,student对象就拥有了SkillImp 类的方法
            skill.getSkill("我会英语");
            student.sayIdentification();
        }
    }
  • 相关阅读:
    TokenType ([{}{}()])[{}]{}
    C# netcore 开发WebService(SoapCore)
    C++求快速幂
    二分法与牛顿迭代法求方程根
    Obtaining a Thorough CS Background Online (线上CS深度学习攻略)
    Elasticsearch 堆空间配置
    S家lic
    如何用calibredrv 来merge多个cell的gds
    siliconsmart feature
    openwrt的IPTV配置
  • 原文地址:https://www.cnblogs.com/xxdsan/p/6496332.html
Copyright © 2011-2022 走看看