Search code examples
javaspring-bootapplication.propertiesspring-contexttomcat10

Tomcat 10 pass Environment Variable or Property to spring boot context


Well, I'm trying to deploy a spring boot application in a tomcat 10 server, passing a one environment key. I need to pass de "secret" of jasypt for decode the passwords in my application, but I can't do this because the context don't run the same as the spring boot application normally.

In my App.java with main loos like

public class App extends SpringBootServletInitializer {

    @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(App.class);
      }
    
      public static void main(String[] args) throws Exception {
        setProp();
        final SpringApplication application = new SpringApplication(AppBatch.class);
        application.run(args);
      }

    private static void setProp() throws Exception {
        // Context ctx = new InitialContext();
        // Context envCtx = (Context) ctx.lookup("java:comp/env");
        // String propertyKey = (String) envCtx.lookup("jasypt.encriptor.password");
        String propertyKey = System.getProperty("jasypt.encriptor.password");
        Properties props = new Properties(System.getProperties());
        if (propertyKey != null && !propertyKey.isEmpty()) {
          props.setProperty("jasypt.encryptor.password", propertyKey);
          System.setProperties(props);
        } else {
          throw new Exception("Not setted property in jasypt password");
        }
    }

}

This code works with an application runs in a normally deploy with Spring Boot, with the

java -jar -Djasypt.encryptor.password="secret" app.jar ...

The code commented is that I tried with tomcat but don't work, the application starts even before that this code, I can't see any log, even this log was in the method configure. But in the tomcat 10, this approach don't work. I need to pass this secret like a property or with the environment. How can I do?


Solution

  • The solution in the end was to create the file setenv.bat in ${TOMCAT_HOME}/bin/setenv.bat

    Following the approach: How to pass the -D additional parameter while starting tomcat?

    The content of setenv.bat:

    set CATALINA_OPTS=%CATALINA_OPTS -Djasypt.encryptor.password="secret"