shurohige
shurohige

Reputation: 31

Create IF conditional inside SpringBootApplication

I am trying to test the resilience of my app, which is deployed in OpenShift along with other apps.

I created a non-static variable in my application.yaml called response

response: 1

I have the SpringBootApplication ready to run

@SpringBootApplication
public class AccountApplication {
      public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class, args);
      }
}

What I want to do, is create a conditional inside the static void to choose if I run the app or not. I tried with

public class AccountApplication {
        @Value("${response}") private int response;
      public static void main(String[] args) {
        if(response==1){
         SpringApplication.run(AccountApplication.class, args);
       }else{}  
      }
}

But I cant use a non-static variable inside an static method. Tried to change my variable to non-static using this https://www.baeldung.com/spring-inject-static-field , but the value was always 0.

How can I do it? I just want an environment variable so I can choose wether my app starts or not to the the resiliency of the other apps.

Upvotes: 0

Views: 283

Answers (1)

devReddit
devReddit

Reputation: 2937

If your target is to make the application fail to run based on the condition, then you can check that non-static value condition using @PostConstruct as below:

@Value("${static.class.value}")
private boolean doRun;


public static void main(String[] args) {
    SpringApplication.run(Demo.class, args);
}


@PostConstruct
private void stopApplication() {
    if (!doRun) {
        throw new RuntimeException("Application forcefully stopped as stopValue in application.properties is true");
    }
}

The application will exit with throwing this exception if the doRun is false

Upvotes: 1

Related Questions