Spring AOP是不够好,完成您的要求。这个小例子给你一个想法:有两个类,每个类有三个共同的方法:play(),addPlayer()和gameover(),每次play方法被调用时程序必须调用例程来打印文本,使用AOP您不需要重复相同的代码。
对于组织为了我将使用一个接口,它不是强制性的,但它是一个很好的做法:
游戏界面:
public interface Game {
void play();
void addPlayer(String name);
void gameOver();
}
足球类实现游戏
public class Soccer implements Game {
@Override
public void play() {
System.out.println("Soccer Play started");
}
@Override
public void addPlayer(String name) {
System.out.println("New Soccer Player added:" + name);
}
@Override
public void gameOver() {
System.out.println("This soccer Game is Over");
}
}
实施游戏的棒球类
public class Baseball implements Game {
@Override
public void play() {
System.out.println("Baseball game started at " + new Date());
}
@Override
public void addPlayer(String name) {
System.out.println("New Baseball Player added: " +name);
}
@Override
public void gameOver() {
System.out.println("The game is over");
}
}
现在的看点配置搭上当打之方法被调用
@Aspect
@Component
public class AspectConfiguration {
@Before("execution(* org.boot.aop.aopapp.interfaces.Game.play(..))")
public void callBefore(JoinPoint joinPoint){
System.out.println("Do this allways");
System.out.println("Method executed: " + joinPoint.getSignature().getName());
System.out.println("******");
}
}
的@Before
注释意味着在执行游戏方法之前的方法将被调用。你也需要指定一个切入点表达式,告诉方面如何匹配你需要触发的方法调用。例如,在这种情况下,我们使用播放方法,它是切入点表达式:"execution(* org.boot.aop.aopapp.interfaces.Game.play(..))"
最后的春天引导应用程序类别:
@EnableAspectJAutoProxy
@SpringBootApplication
public class AopappApplication {
public static void main(String[] args) {
Game soccer=null;
Game baseball=null;
AnnotationConfigApplicationContext ctx = (AnnotationConfigApplicationContext) SpringApplication.run(AopappApplication.class, args);
soccer = (Game) ctx.getBean("soccer");
baseball = (Game) ctx.getBean("baseball");
soccer.play();
baseball.play();
soccer.addPlayer("Player 1");
soccer.addPlayer("Player 2");
baseball.addPlayer("Player 23");
soccer.gameOver();
baseball.gameOver();
}
@Bean("soccer")
public Game soccer(){
return new Soccer();
}
@Bean("baseball")
public Game baseball(){
return new Baseball();
}
}
有上帝文档关于Spring AOP普莱舍看到下面的链接。 Spring AOP Doc.
您不必使用注释处理器。如果足够简单,可以使用Spring AOP。看看一个简单的示例:https://stackoverflow.com/questions/36892410/springboot-logback-configuration或者也可以实现自定义注释:http://www.baeldung.com/spring-aop-annotation它是比实现编译时注释处理器更容易实现和配置。 – Strelok