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