创建好一个Spring Boot工程,添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
新建一个切面:
@Component
@Aspect
class ItemSaveAspect {
@Pointcut("execution(* com.zkong.strategy.entities.Item.save())") //声明一个切点
public void checkItem(){
}
@Before("checkItem()")
public void before(){
System.out.println("before save");
}
@After("checkItem()")
public void after(){
System.out.println("after save");
}
}
其中Item的代码如:
public class Item {
public void save(){
System.out.println("save item");
}
}
新建一个单测,代码如:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ItemTest {
@Test
public void testSave() throws Exception {
Item item = new Item();
item.save();
}
}
此时运行该单测,只打印输出了“save item”。有两个问题:
1)Item并没有添加到Spring容器中,需要在Item上添加@Component
2)单测中的Item实例是new出来的,而非通过Spring容器注入而来,需要修改单测代码为:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ItemTest {
@Autowired
Item item;
@Test
public void testSave() throws Exception {
item.save();
}
}
这样改完后,通知被成功触发。这两个问题都和容器相关,提醒Spring使用者容器的重要性,当有些方法没有触发的时候,不妨检查一下容器中是不是已经有方法所在实例的存在!