Java CDI - Configuration

2

I created a simple project containing a Test class and an InterfaceInterface interface.

In the test interface I created some method just to test. In the Test class I just put @Inject Service service;

When I call the interface method, it is giving nullpointer.

What else is needed to use CDI? I put the weld dependency to use annotations:

    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>2.4.1.Final</version>
    </dependency>

I also created empty beans.xml because I read that you need to have this file.

Can anyone give me strength with the CDI configuration?

    
asked by anonymous 17.01.2017 / 20:42

1 answer

1

It was necessary to know which server you are trying to run on. Home If you are using a post java 6 server beans.xml should already resolve the service, which I imagine is not your case. In this link there is good content.
link

Before proceeding, change your version of maven to artifact-id: weld-servlet:

<dependency>
   <groupId>org.jboss.weld.servlet</groupId>
   <artifactId>weld-servlet</artifactId>
   <version>2.4.1.Final</version>
</dependency>

Assuming you are using the most common for studies, which is Tomcat and is not in a recent version, I will abbreviate the content of the link once your jars have already been provided by maven:

Create a file named context.xml with the contents in the META-INF folder:

<?xml version="1.0" encoding="UTF-8"?>
    <Context>
    <Manager pathname=""/> <!-- disables storage of sessions -->
  <Resource name="BeanManager"
      auth="Container"
      type="javax.enterprise.inject.spi.BeanManager"
      factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>

And add Weld's configuration in web.xml:

<listener>
    <listener-class>   
        org.jboss.weld.environment.servlet.Listener
    </listener-class>
</listener>

<resource-env-ref>
   <resource-env-ref-name>BeanManager</resource-env-ref-name>
   <resource-env-ref-type>
      javax.enterprise.inject.spi.BeanManager
   </resource-env-ref-type>
</resource-env-ref>
    
18.01.2017 / 01:24