有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有办法控制类在wildfly中部署的顺序

此轮询服务用作库(jar文件)

@ApplicationScoped
public class PollingService {

@Inject
protected MessageConsumer consumer;

protected void init(@Observes @Initialized(ApplicationScoped.class) Object o) {
    final Set<String> subscribers = consumer.getSubscribers();
    //for each subscribers there's some task to execute.}}

而订阅服务器是由来自不同项目的其他应用程序范围的类添加的

@ApplicationScoped
public class MessageListener {
private static final Logger logger = LoggerFactory.getLogger(MessageListener.class);
private static final String TEST_QUEUE = "V3-shankar-test";

@Inject
private MessageConsumer consumer;

public void postConstruct(@Observes @Initialized(ApplicationScoped.class) Object o) {
    consumer.subscribe(TEST_QUEUE);
}

在MessageListener类添加订阅服务器之后,是否有任何方法初始化Pollingservice类


共 (2) 个答案

  1. # 1 楼答案

    CDI中没有允许对同一范围内的bean进行初始化排序的机制(@ApplicationScoped在上面的示例中)

    CDI还提供了其他可供使用的功能:

    1. ^{}
    2. 触发特定于应用程序的事件

    带有Instance的代码示例:

    @ApplicationScoped
    public class PollingService {
    
        @Inject
        @Any
        protected Instance<MessageListener> listeners;
    
        protected void init(@Observes @Initialized(ApplicationScoped.class) Object o) {
            for (MessageListener listener : listeners) {
                //for each subscribers there's some task to execute.
            }
        }
    
    }
    

    这里可以通过检测实际listener类上的注释来引入优先级处理,因为代码显式地处理列表


    具有应用程序特定事件的代码示例:

    public class PollingServiceInit {
        private final PollingService service;
        ...
    
        public void subscribe(MessageConsumer consumer) {
            service.subscribe(consumer);
        }
    }
    
    @ApplicationScoped
    public class PollingService {
    
        @Inject
        private Event<PollingServiceInit> event;
    
        protected void init(@Observes @Initialized(ApplicationScoped.class) Object o) {
            event.fire(new PollingServiceInit(this));
        }
    
        void subscribe(MessageListener listener) {
            //for each subscribers there's some task to execute.
        }
    
    }
    
    @ApplicationScoped
    public class MessageListener {
        void onPollingServiceInit(@Observes final PollingServiceInit event) {
            event.subscribe(this);
        }
    }
    
  2. # 2 楼答案

    您可以在每个示例的o参数上放置^{}。通常,它的int类型的元素值是从^{}类的常量中提取或扩充的。观察员方法通知上的specification goes into some detail