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();
        }
    }
  • 相关阅读:
    32-数据链路层,PPP协议
    31-NAT
    30-安全技术,ACL
    ensp实验:配置DHCP
    29-应用层,DHCP协议
    ensp实验:配置stp
    28-STP,选举过程、端口状态、计时器、拓扑变化
    27-交换机,STP
    26-交换机,GVRP
    Manually APK Downgrade for split apks
  • 原文地址:https://www.cnblogs.com/xxdsan/p/6496332.html
Copyright © 2011-2022 走看看