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();
        }
    }
  • 相关阅读:
    软件版本 —— Alpha、Beta、RC版本的区别
    linux删除回收站提示权限错误
    Centos7系统备份和还原脚本
    搭建Docker私服
    在深度Deepin 15.11系统上安装Python 3.7.4版本的方法
    Dockerfile范例
    Remmina无法远程连接的解决方法
    再生龙教程——对于Centos7进行备份和还原
    共享Excel编辑的一些资源
    【转载】怎样编写概要设计
  • 原文地址:https://www.cnblogs.com/xxdsan/p/6496332.html
Copyright © 2011-2022 走看看