Search code examples
spring-bootjardependenciesprogram-entry-pointautowired

Null Pointer Exception using Spring Boot service as a dependency in a batch job


I'm re-using an old, standalone AWT-based Java class which backs up and restores mysql databases.

One thing it needs to do is decrypt a password that it reads from a properties file.

The logic for this is contained in a Spring Boot application.

I'm instantiating the encryption service and decryptor in the standalone class as follows:

DecryptionService decryptionService = new DecryptionService();

The decryptionService uses the @AutoWired annotation to create a decryptor:

@Autowired
private IRSADecryptor decryptor;

For now, I'm running it Eclipse from the same project as the service.

When I try to decrypt the password as follows:

    String decryptedPassword = decryptionService.decryptTextUsingProductKeys("abc");

the debugger show the decryptionService is null.

Here are the first few lines of the stack trace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.ap.services.decryption.service.DecryptionService.decryptTextUsingProductKeys(DecryptionService.java:21)
    at com.ilcore.util.SosaMaintenanceJFrame.jButtonDatabaseBackupActionPerformed(SosaMaintenanceJFrame.java:529)
    at com.ilcore.util.SosaMaintenanceJFrame$6.actionPerformed(SosaMaintenanceJFrame.java:207)

I'm pretty sure I'm not going about this the right way, but I'd like to not have to import the decryption logic. What are my options?


Solution

  • The @Autowired annotation will not create your decryptor object, but will try to locate a Bean of that type and inject it in your DecryptionService. This means that you should not use a constructor to instantiate your DecryptionService. The DecryptionService should be defined as a @Service and injected in another component (@Component, @Controller etc.), from where you will invoke the specific methods for decrypting your data.