As we all know, AspectJ can be enhanced through connection points @ Before, @ After, @ Around such as annotation, today we play a new comment @DeclareParents. A new method for enhancing the target object.
- Scene introduction:
Now we have a class of animal duck, which has a function to swim, but suddenly one day we need to implement a delicious ingredients attribute to animals ducks. We can certainly go duck animal class to add a method, but contrary to the single principle. We can achieve enhanced by AOP.
- Code show time
There is a Animal interface
public interface Animal { void swim(); }
One more animal duck implementation class
@Repository ( "Animal" ) public class DuckAnimal the implements Animal { @Override public void Swim () { System.out.println ( "duck ... like to swim" ); } }
Require an enhanced method to achieve a duck is a delicious food
public interface Food { void EAT (); } @Repository ( "Food" ) public class DuckFood the implements Food { @Override public void EAT () { System.out.println ( "duck look tasty ..." ); } }
Automatic injection
@ComponentScan("com.zjt.springboot.DeclareParents") @Configuration @EnableAspectJAutoProxy public class AppConfiguration { }
Declaring an aspect
@Aspect @Component public class MyAspect { / ** * com.zjt.springboot.DeclareParents.Animal + represents all enhancement subclass of Animal * * = DuckFood.class defaultImpl represents a new class default to add * / the @DeclareParents (value = " . com.zjt.springboot.DeclareParents.Animal + ", defaultImpl = DuckFood class ) public static Food Food; }
Then there is the exciting part of the test:
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(); } }
Test Results:
Ducks like swimming. . .
Ducks look good to eat. . .
Conclusion: From the test results, we found that only an animal Ducks acquired from the container, but you can get the ingredients feature set, and enhancements!