AspectJ之@DeclareParents注解为对象添加新方法
生活随笔
收集整理的這篇文章主要介紹了
AspectJ之@DeclareParents注解为对象添加新方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
眾所周知,AspectJ可以通過@Before,@After,@Around等注解對連接點進行增強,今天我們來玩一個新注解@DeclareParents。對目標對象增強一個新方法。
- 場景引入:
現在我們有一個動物鴨子類,它有個游泳的函數,但是突然有一天我們需要給動物鴨子實現一個很好吃的食材屬性。我們當然可以去動物鴨子類去新增一個方法,但是違背了單一原則。我們可以通過AOP來實現增強。
- Code show time
有一個Animal的接口
public interface Animal {
void swim();
}
再來一個動物鴨子的實現類
@Repository("animal")
public class DuckAnimal implements Animal{
@Override
public void swim() {
System.out.println("鴨子喜歡游泳。。。");
}
}
需要一個增強方法,實現鴨子是一種美味的食物
public interface Food {
void eat();
}
@Repository("food")
public class DuckFood implements Food{
@Override
public void eat() {
System.out.println("鴨子看起來很好吃。。。");
}
}
采用自動注入
@ComponentScan("com.zjt.springboot.DeclareParents")
@Configuration
@EnableAspectJAutoProxy
public class AppConfiguration {
}
聲明一個切面
@Aspect
@Component
public class MyAspect { /**
* com.zjt.springboot.DeclareParents.Animal+ 表示增強Animal的所有子類
*
*defaultImpl=DuckFood.class 表示默認需要添加的新類
*/
@DeclareParents(value="com.zjt.springboot.DeclareParents.Animal+", defaultImpl=DuckFood.class)
public static Food food;
}
接下來就是緊張刺激的測試環節了:
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfiguration.class);
Animal animal = (Animal)context.getBean("animal");
animal.swim();
Food food = (Food)animal;
food.eat();
}
}
測試結果:
鴨子喜歡游泳。。。
鴨子看起來很好吃。。。
結論:從測試結果我們發現,只從容器里獲取了一個動物鴨子,卻可以得到食材的功能,實現了增強功能!
總結
以上是生活随笔為你收集整理的AspectJ之@DeclareParents注解为对象添加新方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Delphi ResourceStrin
- 下一篇: python基本知识点if、while、