code manipulation : dynamic proxy
This commit is contained in:
@@ -3,4 +3,6 @@ package org.example.proxy;
|
||||
public interface BookService {
|
||||
|
||||
void rent(Book book);
|
||||
|
||||
void returnBook(Book book);
|
||||
}
|
||||
|
||||
@@ -14,4 +14,9 @@ public class BookServiceProxy implements BookService {
|
||||
bookService.rent(book);
|
||||
System.out.println("다른기능!!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void returnBook(Book book) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,4 +6,9 @@ public class DefaultBookService implements BookService{
|
||||
public void rent(Book book) {
|
||||
System.out.println("rent: " + book.getTitle());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void returnBook(Book book) {
|
||||
System.out.println("return: " + book.getTitle());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,28 @@ package org.example.proxy;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
public class BookServiceTest {
|
||||
|
||||
BookService bookService = new BookServiceProxy(new DefaultBookService());
|
||||
// BookService bookService = new BookServiceProxy(new DefaultBookService());
|
||||
BookService bookService = (BookService) Proxy.newProxyInstance(
|
||||
BookService.class.getClassLoader(), new Class[]{BookService.class},
|
||||
new InvocationHandler() {
|
||||
BookService bookService = new DefaultBookService();
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if (method.getName().equals("rent")) {
|
||||
System.out.println("로깅!!");
|
||||
Object invoke = method.invoke(bookService, args);
|
||||
System.out.println("다른기능!!");
|
||||
return invoke;
|
||||
}
|
||||
return method.invoke(bookService, args);
|
||||
}
|
||||
});
|
||||
|
||||
@Test
|
||||
public void proxy() {
|
||||
@@ -13,5 +32,6 @@ public class BookServiceTest {
|
||||
book.setTitle("spring");
|
||||
|
||||
bookService.rent(book);
|
||||
bookService.returnBook(book);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user