0

My Spring application depends on certain environment variables that needs to have been set before application launch.

For eg. consider the following controller:

@Controller public class FileUploadController { /** Path to which all data will be uploaded **/ private Path appDataPath; public FileUploadController(){ // Extract the App Data path from environment variables Map<String, String> environmentVariables = System.getenv(); if (environmentVariables.containsKey("MYAPP_DATA_DIR")) { String dataPath = environmentVariables.get("MYAPP_DATA_DIR"); appDataPath = Paths.get(dataPath); } else { // TODO: Throw an exception to terminate app } } } 

What exception do I need to throw in the code above to terminate application startup?

1
  • 1
    Don't do that in your controller... Just use @Value and the application will automatically blow up when it isn't set, you are just complicating things. Commented Sep 28, 2015 at 8:36

2 Answers 2

3

You are making things to complex, either simply inject a String for the path and annotate that with @Value or inject the Environment and use getRequiredProperty either of them will automatically kill the startup of the application.

@Controller public class FileUploadController { @Value("${MYAPP_DATA_DIR}" private String dataPath; private Path appDataPath; @PostConstruct public void init() { appDataPath = Paths.get(dataPath); } } 

Or simply use the Environment abstraction in a @PostConstruct method.

@Controller public class FileUploadController { @Autowired private Environment env; private Path appDataPath; @PostConstruct public void init() { appDataPath = Paths.get(env.getRequiredProperty("MYAPP_DATA_DIR")); } } 

Both will automatically blow up when the property isn't defined.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I wanted! Thanks!
-1

Spring Framework is an implementation of Java Enterprise Container!

By definition of the Java Enterprise Containers, you need to throw subclass of RuntimeException! They are not required to be handled by the container or the calling code.

In case your mandatory environment variables not set and your application cannot start at all then you need to notify and exit.

I would create a SubClass exception from the RuntimeException and use that Exception class!

In case your spring Framework implementation has some strict requirements around (i.e. some Spring subclass of the RuntimeException, ApplicationException ...) then you can subclass that class. But I do not think that Spring is restrictive in this subject...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.