首页 > 编程语言 > 详细

Spring AOP:@DeclareParents 为对象添加方法

时间:2017-03-03 13:47:59      阅读:481      评论:0      收藏:0      [点我收藏+]

通过@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();
    }
}

 

Spring AOP:@DeclareParents 为对象添加方法

原文:http://www.cnblogs.com/xxdsan/p/6496332.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!