@Interceptor
功能:断开逻辑插入功能,比如Logger
定义一个拦截器
LoggedInterceptor.java
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable {
public LoggedInterceptor(){}
// 拦截之后具体实现
@AroundInvoke
public Object logMethod(InvocationContext ctx) throws Exception {
System.out.println("Entering method:" + ctx.getMethod().getName()
+ " in class: " + ctx.getMethod().getDeclaringClass().getName());
return ctx.proceed();
}
}
调用拦截器
@Logged
public void checkin(){
System.out.println("checkin room......");
}
当然拦截器需要在beans.xml
上激活
cn.edu.sdut.r314.AuditInterceptor
cn.edu.sdut.r314.LoggedInterceptor
当然拦截器也可以修饰一整个组件,这样只要调用这个组件的时候就会执行拦截器的内容
@Named
@Audit
public class RoomController {
/**
* 订房
* @return
*/
public void checkin(){
System.out.println("checkin room......");
}
/**
* 退房
* @return
*/
public void checkout(){
System.out.println("checkout room......");
}
}
@Decorator
功能:修饰器,横向
注册一个修饰器类PaintedDecorator.java
@Decorator
public class PaintedDecorator implements Room {
@Inject
@Delegate
Room roomToBeDecorated; //注册被修饰的房子,这里是BlankRoom
public String showRoom() {
doPainting();
return roomToBeDecorated.showRoom() + "刷墙漆";
}
// 刷墙漆
private void doPainting() {
System.out.print("刷墙漆");
}
}
-------------------------------------------------------------------------------------------------------------------
@Decorator
public class FlooredDecorator implements Room {
@Inject
@Delegate
Room roomToBeDecorated; //注册被修饰的房子,这里是BlankRoom
public String showRoom() {
doFlooring();
return roomToBeDecorated.showRoom() + "铺地板";
}
// 铺地板
private void doFlooring() {
System.out.print("装饰地板");
}
}
注册两个被修饰类BlankRoom.java
,修饰的基础
public class BlankRoom implements Room {
public String showRoom() {
return "毛胚房";
}
}
激活修饰器,执行顺序由下至上
cn.edu.sdut.softlab.FlooredDecorator
cn.edu.sdut.softlab.PaintedDecorator
具体实现
@Named("room")
public class RoomController {
@Inject
Room room;
public String showRoom() {
return room.showRoom();
}
}
输出
毛胚房刷墙漆铺地板
示例代码:
https://github.com/liuqinyi/weld-tutorial
https://github.com/liuqinyi/quickstart.git