设定一个场景:X明星要开一场演唱会。我们定义一个表演的接口performance,代表任何形式的表演
interface Performence{
public void show() throws Exception;
}
这个show方法抛出异常,说明这场演唱会可能会在中途出现意外,音响坏了、停电了、甚至X明星心脏病犯了·····
下面我们创建一个演唱会类SongPerformence
@Component
class SongPerformence implements Performence{
public void show() throws Exception {
System.out.println("演唱会。。。");
throw new Exception("演唱会搞砸了...");
}
}
好吧,我是存心想让演唱会出现点意外。。。
可以看到SongPerformence类中只专注于表演,并不在乎观众的感受,但是这不代表观众的感受不重要,至少通过观众的感受可以看出X明星的表演效果是否成功!只是在表演过程中X明星需要专注于表演,至于观众的感受我们可以让其他工作人员去记录(AOP)。
我们定义观众类(严格意义来说应该是观察者类)
@Aspect//@Aspect注解可以声明一个切面
@Component
class Audience{
//定义切点pointCut
@Pointcut("execution(* com.spring.aop.Performence.show(..))")
public void pointCut(){}
/**
* 表演开始前 关闭手机
* @auth chenhui
*/
@Before("pointCut()")
public void shutdownPhone(){
System.out.println("关闭手机...");
}
/**
* 表演前 找到你的座位号
*/
@Before("pointCut()")
public void findSeat(){
System.out.println("找到你的座位号...");
}
@AfterReturning("pointCut()")
public void sayGood(){
System.out.println("show很不错。。。");
}
@AfterThrowing("pointCut()")
public void backTicket(){
System.out.println("表演失败,要求退票...");
}
}
我们可以在这里看到观众在演唱会开始前后的一些表现。
@Aspect注解可以声明一个切,同时需要运用@EnableAspectJAutoProxy//启用AspectJ自动代理
@Configuration
@EnableAspectJAutoProxy//启用AspectJ自动代理
@ComponentScan
class Config{
}
我们可以利用AOP来记录观众的感受
这样X明星可以专注于表演,而不必分心去关注观众的评价
测试一下
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=Config.class)
public class AopJTest {
@Autowired
private Performence performence;
@Autowired
private Audience audience;
@Test
public void test() throws Exception{
performence.show();
}
}
结果