是一个开源项目。
是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。Hibernate支持它来实现PO(Persistent Object 持久化对象)字节码的动态生成。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@SpringBootTest
public class BookTest {
@Autowired Book book;
@Test
public void testMethod(){
// CGLIB代理的原理,创建被代理类的子类,子类拥有父类的所有方法
// 创建增强器
Enhancer enhancer = new Enhancer();
// 指定给那个类增强
enhancer.setSuperclass(book.getClass());
// 此方法用于有接口的类
// 指定增强方法
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
if("look".equals(method.getName())){
System.out.println("增强");
book.look();
}else if("study".equals(method.getName())) {
System.out.println("增强");
book.study();
}
return null;
}
});
// 创建CGLIB
Book book = (Book) enhancer.create();
book.study();
book.look();
}
2558

被折叠的 条评论
为什么被折叠?



