Saad
Saad

Reputation: 907

@Inject not working for CDI bean

I am trying a very simple example on JBOSS.

I have following class defined

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject; 

@Singleton
@Startup
public class PRCConnectionRunner {

@Inject
private PRCConfiguration prcConfiguration;

@PostConstruct
void printthing() {
    System.out.println("HI");

    System.out.println(prcConfiguration== null);
}   

}


public class PRCConfiguration {
 public String greet(String name) {
        return "Hello, " + name + ".";
    }
}

I have my beans.xml defined in the WEB-INF directory and i am packaging this as a war from maven.

However when i deploy and start this on JBOSS server, I do get the HI printed but the dependency is not injected because i get true for the null test. What am i doing wrong? I believe since @PostConstruct method is invoked i am missing some small detail.

Upvotes: 3

Views: 10799

Answers (2)

Milkmaid
Milkmaid

Reputation: 1754

From CDI 1.1 not every class are managed by CDI context. You have to specified it by annotation or put bean-discovery-mode="ALL" in your beans.xml, then use @Vetoed on class which should not be managed by CDI. Default value is bean-discovery-mode="ANNOTATED". My recommendation is annotate your class with proper annotation(depends on life cycle of the bean).

Also check if your bean.xml file is located in ..\webapp\WEB-INF\beans.xml

Default CDI Enablement in Java EE 7

Upvotes: 1

Saad
Saad

Reputation: 907

I resolved it. The issue was beans.xml was stored in an incorrect location.

The beans.xml should always be at for a web application.

src\main\webapp\WEB-INF\beans.xml

If you use eclipse/jboss, a quick way is to just check if the deployed resources menu is populating the beans.xml. When i placed it at the right location, jboss automatically updated the deployed resources menu item.

enter image description here

Upvotes: 2

Related Questions