一般的Springboot工程整合h2数据库的时候,如果需要开启远程连接
非常的简单,在applications里面进行配置即可
#配置数据库h2的参数
#spring.datasource.url=jdbc:h2:file:h2
#spring.datasource.driver-class-name=org.h2.Driver
#spring.datasource.username=root
#spring.datasource.password=123456
#在浏览器中开启控制台
#spring.h2.console.enabled=true
#spring.h2.console.path=/h2-console
#spring.h2.console.settings.trace=true
##spring.h2.console.settings.web-allow-others=true
但是如果整合了Springsecurity的时候,这个配置文件配置的内容就失效了,此时需要做的是,在SpringSecurity的WebConfig里面进行注入
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
registrationBean.addUrlMappings("/h2-console/*");
//允许远程访问h2-console
registrationBean.addInitParameter("webAllowOthers", "");
registrationBean.addInitParameter("trace", "");
return registrationBean;
}
并且需要在SpringSecurity拦截配置中将h2数据库的url进行放开,不被拦截
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 禁用csrf
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
//放开拦截
http.authorizeRequests().antMatchers("/h2-console/**").permitAll()
}
}