Charles Morin
Charles Morin

Reputation: 1447

Field injection works but constructor injection returns NullPointerException

While looking at an existing Spring application, I stumbled upon a class with field injection, which we all know isn't recommended for various reasons. I have then decided to refactor it to make use of a more appropriate approach: constructor based DI.

Before refactoring

@Component
public class MaintenanceModeInterceptor implements HandlerInterceptor {

    private static final String MAINTENANCE_MODE_VIEW = "common/maintenanceMode";

    @Autowired  
    private ApplicationObject applicationObject;

    public MaintenanceModeInterceptor() {
        // Required by Spring
    }
...
}

After refactoring

@Component
public class MaintenanceModeInterceptor implements HandlerInterceptor {

    private static final String MAINTENANCE_MODE_VIEW = "common/maintenanceMode";

    private ApplicationObject applicationObject;

    public MaintenanceModeInterceptor() {
        // Required by Spring
    }

    @Autowired  
    public MaintenanceModeInterceptor(ApplicationObject applicationObject) {
        this.applicationObject = applicationObject;
    }
...
}

Maybe it is related to the fact that a default constructor is present. However, if I remove it, I end up having this exception:

Caused by: java.lang.NoSuchMethodError: my.application.web.interceptor.MaintenanceModeInterceptor: method <init>()V not found

So my understanding is that Spring requires a default constructor for interceptors.

Is there any way to achieve construtor based DI in this scenario?

Thank you.

Upvotes: 2

Views: 640

Answers (1)

pleft
pleft

Reputation: 7905

I think you should remove the non @Autowired constructor and do perform a clean build on your project.

Upvotes: 1

Related Questions