0

I have an Apex class with two constructors. When I call an @AuraEnabled method from the helper, it does not hit any of the constructors. How can I specify a constructor from the helper?

Thanks

1
  • @AuraEnabled method has nothing to do with constructors as they operate in static context
    – Jayant Das
    Sep 21, 2018 at 13:42

1 Answer 1

2

Apex server-side controllers for Lightning components use methods that are declared static and @AuraEnabled. Since static methods are not bound to an object instance, the constructor is never called during a server call from Lightning.

static methods don't get to maintain state between calls in instance variables. All of your state should be kept client-side, in your JavaScript controller or component attributes. Any initialization that must be done server-side has to be done in a static context, not in a constructor, unless the constructor is for some object that is itself instantiated within the static method.

Here's an example.

public class SampleController {
    private String myInstanceVar;
    public SampleController() {
        myInstanceVar = 'Test';
    }

    @AuraEnabled static void lightningControllerMethod() {
        // Here, `SampleController()` is never called
        // We can't access `myInstanceVar` in static context.
        String myLocalInstanceVar = 'Test'; // this is fine.
    }

    @AuraEnabled static void anotherLightningControllerMethod() {
        myCustomObject q = new MyCustomObject('Test');
        // myCustomObject() constructor *is* called, because we instantiated it here.
        // We still can't access `myInstanceVar`.
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .