Как заставить внедрение зависимости работать в профиле Liberty - PullRequest
1 голос
/ 08 октября 2019

Я не могу заставить внедрение зависимостей работать в профиле Liberty. Вот что я попробовал:

server.xml выдержки:

<featureManager>
    <feature>javaee-8.0</feature>
    <feature>localConnector-1.0</feature>
</featureManager>

<managedExecutorService jndiName="concurrent/execSvc" id="Test1">
</managedExecutorService>

Мой код. Обратите внимание на некоторые из моих многочисленных @Resource попыток.

import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

import javax.ws.rs.Path;

@Path("/hello")
public class HelloResource
{
    final static Logger logger = Logger.getLogger(HelloResource.class.getName());

//  @Resource(lookup="java:comp/env/concurrent/execSvc")
//  @Resource(lookup="java:comp/concurrent/execSvc")
//  @Resource(lookup="concurrent/execSvc")
//  @Resource(lookup="Test1")
//  @Resource(name="java:comp/concurrent/execSvc")
//  @Resource(name="concurrent/execSvc")
//  @Resource(name="Test1")
    @Resource       // with different names tried in <managedExecutorService> in server.xml 
    private ManagedExecutorService executor;

    @GET
    @Produces("text/plain")
    public String getMessage()
    {
        logger.info("HelloResource::getMessage()");

        int startTimeout = 10;
        String msg = "??";

        if (executor != null)
        {
            logger.info("Before Runnable Start");
            executor.execute(new RunnableTask(startTimeout));     
            logger.info("After Runnable Start");

            msg = "RunnableTask submitted";
        }
        else
        {
            logger.severe("executor is null");
            msg = "null executor";
        }

        return msg;
    }
}

Я установил след: Naming=all:NamingService=all:org.apache.aries.jndi.*=all

Никаких подсказок, которые я вижу в trace.log:

[10/7/19 15:30:05:297 MST] 000000d8  I UOW= source=com.ibm.ws.app.manager.AppMessageHelper org= prod= component=
          CWWKZ0018I: Starting application JchJaxRsTestApp.
[10/7/19 15:30:05:298 MST] 000000d8  I UOW= source=com.ibm.ws.app.manager.war.internal.WARDeployedAppInfoFactoryImpl org= prod= component=
          CWWKZ0134I: The JchJaxRsTestApp application is using the loose application definition at the D:\jchprodtemp\WAS Liberty Profile - 19.0.0.9\wlp\usr\servers\JchJaxRsTest\apps\JchJaxRsTestApp.war.xml location.
[10/7/19 15:30:05:307 MST] 000000d8  > UOW= source=com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaColonNameService method=applicationMetaDataCreated id=50d82b52 org= prod= component=
          Entry  
          com.ibm.ws.container.service.metadata.internal.MetaDataEventImpl@7769e37e[com.ibm.ws.container.service.app.deploy.internal.ApplicationMetaDataImpl@13d9cb7a[JchJaxRsTestApp], com.ibm.ws.adaptable.module.internal.AdaptableContainerImpl@5802a4c8 ( file:/D:/jch/Prog/Java/Eclipse/workspace-jee-2019-09-R/JchJaxRsTestApp/WebContent/ file:/D:/jchprodtemp/WAS%20Liberty%20Profile%20-%2019.0.0.9/wlp/usr/servers/JchJaxRsTest/workarea/org.eclipse.osgi/71/data/cacheAdapt/com.ibm.ws.app.manager_44/.overlay/ )]
[10/7/19 15:30:05:307 MST] 000000d8  < UOW= source=com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaColonNameService method=applicationMetaDataCreated id=50d82b52 org= prod= component=
          Exit 
[10/7/19 15:30:05:337 MST] 000000d8  > UOW= source=com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaColonNameService method=moduleMetaDataCreated id=50d82b52 org= prod= component=
          Entry  
          com.ibm.ws.container.service.metadata.internal.MetaDataEventImpl@375e5fbb[com.ibm.ws.webcontainer.osgi.metadata.WebModuleMetaDataImpl@5bcc4e41[JchJaxRsTestApp#JchJaxRsTestApp.war], com.ibm.ws.adaptable.module.internal.AdaptableContainerImpl@5802a4c8 ( file:/D:/jch/Prog/Java/Eclipse/workspace-jee-2019-09-R/JchJaxRsTestApp/WebContent/ file:/D:/jchprodtemp/WAS%20Liberty%20Profile%20-%2019.0.0.9/wlp/usr/servers/JchJaxRsTest/workarea/org.eclipse.osgi/71/data/cacheAdapt/com.ibm.ws.app.manager_44/.overlay/ )]
[10/7/19 15:30:05:337 MST] 000000d8  < UOW= source=com.ibm.ws.jndi.url.contexts.javacolon.internal.JavaColonNameService method=moduleMetaDataCreated id=50d82b52 org= prod= component=
          Exit 
[10/7/19 15:30:05:337 MST] 000000d8  > UOW= source=com.ibm.ws.container.service.naming.JavaColonNamespaceBindings method=<init> org= prod= component=
          Entry  
          java:module
          com.ibm.ws.ejbcontainer.osgi.internal.naming.EJBJavaColonNamingHelper@41327753
[10/7/19 15:30:05:338 MST] 000000d8  < UOW= source=com.ibm.ws.container.service.naming.JavaColonNamespaceBindings method=<init> id=5cd245da org= prod= component=
          Exit  
          {}
[10/7/19 15:30:05:338 MST] 000000d8  I UOW= source=com.ibm.ws.webcontainer.osgi.webapp.WebGroup org= prod= component=
          SRVE0169I: Loading Web Module: JchJaxRsTestApp.
[10/7/19 15:30:05:338 MST] 000000d8  I UOW= source=com.ibm.ws.webcontainer class=com.ibm.ws.webcontainer.osgi.DynamicVirtualHost method=addWebApplication org= prod= component=
          SRVE0250I: Web Module JchJaxRsTestApp has been bound to default_host.
[10/7/19 15:30:05:338 MST] 000000d8  A UOW= source=com.ibm.ws.http.internal.VirtualHostImpl org= prod= component=
          CWWKT0016I: Web application available (default_host): http://localhost:9080/JchJaxRsTestApp/
[10/7/19 15:30:05:339 MST] 000000d8  A UOW= source=com.ibm.ws.app.manager.AppMessageHelper org= prod= component=
          CWWKZ0003I: The application JchJaxRsTestApp updated in 0.042 seconds.
[10/7/19 15:30:05:341 MST] 00000074  > UOW= source=com.ibm.ws.container.service.naming.JavaColonNamespaceBindings method=<init> org= prod= component=
          Entry  
          java:comp/env
          com.ibm.ws.injectionengine.osgi.internal.InjectionBindingClassNameProvider@145355cc
[10/7/19 15:30:05:341 MST] 00000074  < UOW= source=com.ibm.ws.container.service.naming.JavaColonNamespaceBindings method=<init> id=567006bd org= prod= component=
          Exit  
          {}
[10/7/19 15:30:05:341 MST] 00000074  I UOW= source=com.ibm.ws.session.WASSessionCore class=SessionContextRegistryImpl method=getSessionContext org= prod= component=
          SESN0176I: A new session context will be created for application key default_host/JchJaxRsTestApp
[10/7/19 15:30:05:342 MST] 00000074  I UOW= source=com.ibm.ws.util class=IDGeneratorImpl method=IDGeneratorImpl org= prod= component=
          SESN0172I: The session manager is using the Java default SecureRandom implementation for session ID generation.
[10/7/19 15:30:05:350 MST] 00000074  I UOW= source=org.apache.myfaces.ee.MyFacesContainerInitializer org= prod= component=
          Using org.apache.myfaces.ee.MyFacesContainerInitializer
[10/7/19 15:30:05:414 MST] 0000008c  I UOW= source=com.ibm.ws.webcontainer.osgi.mbeans.PluginGenerator org= prod= component=
          SRVE9103I: A configuration file for a web server plugin was automatically generated for this server at D:\jchprodtemp\WAS Liberty Profile - 19.0.0.9\wlp\usr\servers\JchJaxRsTest\logs\state\plugin-cfg.xml.
[10/7/19 15:30:05:466 MST] 000000dc  I UOW= source=com.ibm.ws.webcontainer.osgi.mbeans.PluginGenerator org= prod= component=
          SRVE9103I: A configuration file for a web server plugin was automatically generated for this server at D:\jchprodtemp\WAS Liberty Profile - 19.0.0.9\wlp\usr\servers\JchJaxRsTest\logs\state\plugin-cfg.xml.
[10/7/19 15:30:14:688 MST] 0000009b  I UOW= source=org.apache.cxf.endpoint.ServerImplorg.eclipse.osgi.internal.loader.EquinoxClassLoader@7a1a844a[com.ibm.ws.org.apache.cxf.cxf.core.3.2:1.0.32.cl190920190905-0148(id=195)] org= prod= component=
          Setting the server's publish address to be /rest/
[10/7/19 15:30:14:692 MST] 0000009b  I UOW= source=com.ibm.ws.webcontainer.servlet class=com.ibm.ws.webcontainer.servlet.ServletWrapper method=init org= prod= component=
          SRVE0242I: [JchJaxRsTestApp] [/JchJaxRsTestApp] [jch.jaxrstest.App]: Initialization successful.
[10/7/19 15:30:14:698 MST] 0000009b  I UOW= source=jch.jaxrstest.HelloResource org= prod= component=
          HelloResource::getMessage()
[10/7/19 15:30:14:698 MST] 0000009b  E UOW= source=jch.jaxrstest.HelloResource org= prod= component=
          executor is null

Чего мне не хватает?

Ответы [ 2 ]

2 голосов
/ 10 октября 2019

Ресурсы по умолчанию не включены CDI по умолчанию. Добавьте следующее к вашему HelloResource классу @RequestScoped после @Parth

Тогда это будет работать:


    @Resource(lookup="concurrent/execSvc")
    ExecutorService executorService;

, где server.xml содержит следующее (я настоятельно рекомендую толькодобавляя функции, которые вам действительно нужны, сервер будет запускаться быстрее и потреблять меньше ресурсов. javaee-8.0 приносит много вещей, которые вам обычно не нужны):

    <!-- Enable features -->
    <featureManager>
        <feature>cdi-2.0</feature>
        <feature>concurrent-1.0</feature>
        <feature>jaxrs-2.1</feature>
        <feature>localConnector-1.0</feature>
        <feature>servlet-4.0</feature>
    </featureManager>

    ....
    <managedExecutorService jndiName="concurrent/execSvc"/>

в выводе из класса:

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getHello() {
        System.out.println("rest called: " + executorService);
        return "hello ";
    }

Я вижу, как правильно введен исполнитель:

rest called: com.ibm.ws.concurrent.internal.ManagedExecutorServiceImpl@5f9d9066
1 голос
/ 10 октября 2019

Другим решением было бы добавить файл beans.xml в веб-проект и настроить beans.xml с bean-discovery-mode="all".

См. Также это объяснение: http://mjremijan.blogspot.com/2016/09/cdi-inject-beans-into-path-jax-rs.html

...