Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependecy Injection causing Null Pointer Exception

OK I have been following this tutorial about Web Sockets, And I understand 99% of how the example code works. As for the 1%, it deals with the Dependency Injection. After researching DI, I understand that classes become dependent on a object from a class(ether itself or some other) in order to function. Here is how it is used.

package org.example.websocket;

...
import javax.websocket.server.ServerEndpoint;
import javax.inject.Inject;

@ApplicationScoped
@ServerEndpoint("/actions")
public class DeviceWebSocketServer {

    @Inject
    private DeviceSessionHandler sessionHandler;

    @OnOpen
    public void open(Session session) {
    }

    ...
}

I understand that the theory here is the class "DeviceWebSocketServer" is dependent on "DeviceSessionHandler" in order to function. However, when I run this code I get java.lang.NullPointerException in the logcat.

So I found out that the reason why is because sessionHandler is never initialized and is just hanging out being null and throwing Exceptions around like they are free. Isn't that purpose of the @Inject to prevent this? I am able to prevent the NPE by changing....

private DeviceSessionHandler sessionHandler = new DeviceSessionHandler();

But then the application does not behave like the tutorial says it should under
Testing the Java WebSocket Home Application
Step 4: A device is added to the Java WebSocket Home server and it is rendered in both web browsers.

Both Browsers are not updated. Now I don't know if that because of the DI work around, or some other factor. I need help figuring out why the Dependency Injection is not working, and then I can make a determination if that is the cause of differing results.

I can post more code or logcat or whatever you think may be of help. Thanks!

like image 692
chewpoclypse Avatar asked May 22 '26 19:05

chewpoclypse


1 Answers

Glad you realized that without @Inject, you simply need to new a handler for it, but, that's not good enough, you also need static for it, because you want all of clients sharing the same handler, then any of the client updates the device, all the other clients can see it, I tested it, it worked.

For your second question, besides adding static for that handler, and since you are not using GlassFish, I assume you may need to include the GlassFish "javax.json" lib, or if you are using maven to manage the imports, you should add the GlassFish implementation, instead of only declaration, so you should add:

 <dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.0.4</version>
</dependency>
like image 73
ccjli Avatar answered May 24 '26 10:05

ccjli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!