官术网_书友最值得收藏!

  • Jakarta EE Cookbook
  • Elder Moraes
  • 168字
  • 2021-06-24 16:12:35

How to do it...

This recipe will show you one of the main features introduced by CDI 2.0: ordered observers. Now, you can turn the observer's job into something predictable:

  1. First, let's create an event to be observed:
public class MyEvent {

private final String value;

public MyEvent(String value){
this.value = value;
}

public String getValue(){
return value;
}
}
  1. Now, we build our observers and the server that will fire them:
public class OrderedObserver {

public static void main(String[] args){
try(SeContainer container =
SeContainerInitializer.newInstance().initialize()){
container
.getBeanManager()
.fireEvent(new MyEvent("event: " +
System.currentTimeMillis()));
}
}

public void thisEventBefore(
@Observes @Priority(Interceptor.Priority
.APPLICATION - 200)
MyEvent event){

System.out.println("thisEventBefore: " + event.getValue());
}

public void thisEventAfter(
@Observes @Priority(Interceptor.Priority
.APPLICATION + 200)
MyEvent event){

System.out.println("thisEventAfter: " + event.getValue());
}
}

  1. Also, don't forget to add the beans.xml file to the META-INF folder:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
  1. Once you run it, you should see a result like this:
INFO: WELD-ENV-002003: Weld SE container 
353db40d-e670-431d-b7be-4275b1813782 initialized

thisEventBefore: event -> 1501818268764
thisEventAfter: event -> 1501818268764

Now, let's see how this works.

主站蜘蛛池模板: 安多县| 花莲县| 昌图县| 青田县| 嘉善县| 雷山县| 大安市| 略阳县| 龙州县| 天气| 灌阳县| 福州市| 庄浪县| 黄冈市| 浙江省| 沙洋县| 道真| 大理市| 尤溪县| 即墨市| 邵东县| 宾川县| 徐闻县| 凯里市| 北川| 正蓝旗| 塔河县| 南丹县| 景宁| 荃湾区| 库伦旗| 砀山县| 昭苏县| 和田县| 疏附县| 邻水| 益阳市| 治县。| 南充市| 崇文区| 陆良县|