Expand my Community achievements bar.

How to getRunModes() in java class?

Avatar

Level 4

Hi all,

I want to get the run mode of the AEM in java class. My code as below

package com.abc.xyz.core.models;
import com.com.abc.xyz.core.exception.HostConfigurationException;
import com.com.abc.xyz.core.utility.ApiManagementConfiguration;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;

import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Component;
import org.apache.sling.settings.SlingSettingsService;

public class HostConfigUtill {

   @Reference
   private static SlingSettingsService slingSettingsService;

  public static ApiManagementConfiguration getHost(ResourceResolver resourceResolver) {

  String hostConfiguration = "hostconfiguration";

  if(slingSettingsService.getRunModes().contains("local") == true){

  hostConfiguration = "hostconfiguration";
   }else if(slingSettingsService.getRunModes().contains("prod") == true){

  hostConfiguration = "hostconfiguration.prod";
   }else if(slingSettingsService.getRunModes().contains("uat") == true){

  hostConfiguration = "hostconfiguration.uat";
   }else if (slingSettingsService.getRunModes().contains("dev") == true){

  hostConfiguration = "hostconfiguration.dev";
   }

When I debug to the code, the slingSettingsService variable is null . So I can't get the run mode. Why the slingSettingsService is null? How to get the run mode?

Thanks you so much!

BienHV

1 Reply

Avatar

Level 10

This util class is not a component or a sling model hence you can't use @Reference in it. Modify it to @Component to make it work.

Check this example-

acs-aem-commons/ModeUtil.java at master · Adobe-Consulting-Services/acs-aem-commons · GitHub