简体   繁体   中英

CDI - Injection not resolved

I've this class:

@ApplicationScoped
public class ConfigurationResources {...}

By other hand, I'm using ConfigurationResources inside a ClientAuthzService :

public class ClientAuthzService {
    @Inject protected ConfigurationResources configurationResources;
    //...
}

I'm injecting it when a request an endpoint is reached to my JAXRS interface:

public class ClientAuthzEndpoint implements IClientAuthzEndpoint {
    @Inject private ClientAuthzService clientAuthzService;
    //...
}

and IClientAuthzEndpoint :

@Path(value = "/client")
@Produces(MediaType.APPLICATION_JSON)
public interface IClientAuthzEndpoint {

However, ConfigurationResources is not injected inside a ClientAuthService :

public ClientAuthzService()
    {
        this.mongoUserRepository = new UserMongoRepository(
            new MongoContextSource(
                this.configurationResources.getMongodbServer(),
                this.configurationResources.getMongodbPort(),
                this.configurationResources.getMongodbDatabase(),
                this.configurationResources.getMongodbUsername(),
                this.configurationResources.getMongodbPassword(),
                this.configurationResources.getMongodbAuthenticationDatabase()
            )
        );

I'm getting a NullReferenceException due to configurationResources is null !

Any ideas?

You cannot access injected objects from a constructor. CDI needs to be able to construct the object before injecting stuff into it.

You can perform any initialisation that you need in an @PostConstruct annotated method:

public class ClientAuthzService {

    @Inject
    private ConfigurationResources configurationResources;

    private UserMongoRepository mongoUserRepository;

    public ClientAuthzService() {
    }

    @PostConstruct
    void initialise() {
        this.mongoUserRepository = new UserMongoRepository(
            new MongoContextSource(
                this.configurationResources.getMongodbServer(),
                this.configurationResources.getMongodbPort(),
                this.configurationResources.getMongodbDatabase(),
                this.configurationResources.getMongodbUsername(),
                this.configurationResources.getMongodbPassword(),
                this.configurationResources.getMongodbAuthenticationDatabase()
            )
        );
    }

    ...
}

Make sure your ClientAuthzEndpoint is a valid bean(is inside CDI context). try to add above your class:

@Named
@RequestScoped

In other words. Make sure that all classes where you are using @Inject is valid bean thus has proper annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM