AOP(Aspect Oriented Programming)面向切面的編程
簡單點說就是對一個方法執行的特殊點插入一些處理,在這些點執行這些特殊的處理。
例如BookService的showBookInfo方法,咱們在該方法的Before,After,Around,AfterReturning,AfterThrowing等特殊點插入執行一些特殊的處理。java
幾個術語:
鏈接點(Join point):可以被攔截的地方
切點(Pointcut):處理的方法。即上面提到的showBookInfo方法
加強/通知(advice):添加到切點的處理。上面提到的Before, After, AfterReturning, AfterThrowing
織入(Weaving):將加強/通知添加到具體類的切點的過程
切面(Aspect):有切點和加強/通知組成git
BookService.javagithub
public interface BookService { public void showBookInfo(Book book); }
BookServiceImpl.javaspring
@Service public class BookServiceImpl implements BookService { @Override public void showBookInfo(Book book) { if (book == null) { throw new RuntimeException("null object"); } System.out.print("Bookid:"+ book.getID()); System.out.print("\t BookName:" + book.getName()); System.out.println("\t Author:" + book.getAuthor()); } }
showBookInfo就是咱們的切點編程
BookServiceAspect.javaspringboot
@Aspect public class BookServiceAspect { @Pointcut("execution(* com.springboot.aop.test.service.BookServiceImpl.showBookInfo(..))") public void pointCut() { } @Before("pointCut()") public void before() { System.out.println("-------before........."); } @Around("pointCut()") public void around(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("-------around before........."); pjp.proceed(); System.out.println("-------around after........."); } @After("pointCut()") public void after() { System.out.println("-------after........."); } @AfterReturning("pointCut()") public void afterReturning() { System.out.println("-------afterReturning........."); } @AfterThrowing("pointCut()") public void afterThrowing() { System.out.println("-------afterThrowing........."); } }
對加強/通知添加了對應的處理。app
BookAOPController.javaide
@RestController @RequestMapping("/book") public class BookAOPController { @Autowired private BookService bookService = null; @ResponseBody @GetMapping("/showbookinfo") public Book showBookInfo(@RequestParam String bookID, @RequestParam String bookName, @RequestParam String author) { Book book = null; if (bookID != null) { book = new Book(); book.setID(bookID); book.setName(bookName); book.setAuthor(author); } bookService.showBookInfo(book); return book; } }
SpringbookAopApplication.java測試
@SpringBootApplication public class SpringbootAopApplication { @Bean(name="bkServiceAspect") public BookServiceAspect initAspect() { return new BookServiceAspect(); } public static void main(String[] args) { SpringApplication.run(SpringbootAopApplication.class, args); } }
測試
spa
能夠看到咱們的切點對應的加強/通知中的處理都執行了
示例代碼在SpringbootAOP