Skip to content

Instantly share code, notes, and snippets.

@Forinil
Created March 30, 2019 18:06
Show Gist options
  • Save Forinil/b79d7a9ed122d2b26cfb9e310094eaa0 to your computer and use it in GitHub Desktop.
Save Forinil/b79d7a9ed122d2b26cfb9e310094eaa0 to your computer and use it in GitHub Desktop.
@Configuration
@EnableConfigurationProperties(H2ConfigProperties.class)
public class H2Config extends H2ConsoleAutoConfiguration {
private static final String FIELD_NAME = "GENERIC";
private static final String FIELD_MODIFIERS = "modifiers";
@Value("${spring.datasource.driver-class-name}")
private String connectionDriver;
@Value("${spring.datasource.url}")
private String connectionUrl;
@Value("${spring.datasource.username}")
private String connectionUserName;
private H2ConfigProperties.Custom custom;
public H2Config(H2ConfigProperties properties) {
super(properties);
this.custom = properties.getCustom();
logger.debug("Checking if custom console is enabled: {}", custom.isEnabled());
}
@Bean
@Override
@ConditionalOnProperty(prefix = "spring.h2.console.custom", name = "enabled", havingValue = "true")
public ServletRegistrationBean<WebServlet> h2Console(){
String[] connectionList = new String[]{String.format("In-memory test DB|%s|%s|%s", connectionDriver, connectionUrl, connectionUserName)};
try {
Field genericField = WebServer.class.getDeclaredField(FIELD_NAME);
genericField.setAccessible(true);
Field modifiers = Field.class.getDeclaredField(FIELD_MODIFIERS);
modifiers.setAccessible(true);
modifiers.setInt(genericField, genericField.getModifiers() & ~Modifier.FINAL);
genericField.set(null, connectionList);
} catch (NoSuchFieldException | IllegalAccessException e) {
logger.error("Error setting JDBC connection URL in Console Servlet", e);
}
return super.h2Console();
}
}
@ConfigurationProperties(prefix = "spring.h2.console")
public class H2ConfigProperties extends H2ConsoleProperties {
@Getter
private final Custom custom = new Custom();
@Getter
@Setter
public static class Custom {
/**
* Enable the custom console.
*/
private boolean enabled = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment