【Spring Boot 实战与进阶】AOP 的两种动态代理,java 注解的实现原理
1、BookDaoImpl
@Repository
public class BookDaoImpl implements BookDao {
@Override
public void addBook(String name, String author) {
System.out.println("BookDaoImpl 实现类:bookName:"+name+", bookAuthor:"+author);
}
}
2、BookAop
@Component
@Aspect
public class BookAop {
// 定义切入点
public static final String POINT_CUT = "execution(* com.example.bootaop.dao...(..))";
@Before(POINT_CUT)
public void before() {
System.out.println("----------添加图书方法前[校验]-----------");
}
@After(POINT_CUT)
public void after(JoinPoint jp) {
System.out.println("----------添加图书成功后-----------");
System.out.println(jp.getTarget().getClass());
System.out.println(Arrays.asList(jp.getArgs()));
}
}
3、BootAopApplication
@SpringBootApplication
public class BootAopApplication {
public static void main(String[] args) {
ConfigurableApplicationContext
context = SpringApplication.run(BootAopApplication.class, args);
BookDaoImpl bookDao = context.getBean(BookDaoImpl.class);
System.out.p
rintln(bookDao.getClass());
bookDao.addBook("神雕侠侣", "金庸");
context.close();
}
}
控制台输出
class com.example.bootaop.dao.BookDaoImpl
2d857802
----------添加图书方法前[校验]-----------
BookDaoImpl 实现类:bookName:神雕侠侣, bookAuthor:金庸
----------添加图书成功后-----------
class com.example.bootaop.dao.BookDaoImpl
[神雕侠侣, 金庸]
1、BookDao
@Repository
public class BookDaoImpl1 implements BookDao {
@Override
public void addBook(String name, String author) {
}
}
2、BookDaoImpl1
@Repository
public class BookDaoImpl1 implements BookDao {
@Override
public void addBook(String name, String author) {
}
}
3、BootAopApplication
@SpringBootApplication
public class BootAopApplication {
public static void main(String[] args) {
ConfigurableApplicationContext
context = SpringApplication.run(BootAopApplication.class, args);
BookDao bookDao = context.getBean("bookDaoImpl1", BookDao.class);//多个实现类时
System.out.println(bookDao.getClass());
bookDao.addBook("鹿鼎记", "金庸");
context.close();
}
}
配置文件增加:spring.aop.proxy-target-class=false
控制台输出
class com.sun.proxy.$Proxy61
----------添加图书方法前[校验]-----------
评论