简体   繁体   English

Springboot:注入bean时ScriptUtils不会在H2中播种数据

[英]Springboot: ScriptUtils does not seed data in H2 when beans are injected

I have a working springboot application.我有一个工作的 springboot 应用程序。 At startup it executes a sql script to seed some test data in the H2 database.在启动时,它会执行 sql 脚本以在 H2 数据库中播种一些测试数据。 I just used this and it worked fine so far.我刚用过这个,到目前为止效果很好。

spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
  datasource:
    url: jdbc:h2:mem:portalDB;LOCK_TIMEOUT=10000;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    driver-class-name: org.h2.Driver
    username: sa
    password:
    hikari:
      pool-name: springHikariCP
      connection-timeout: 30000
      maximum-pool-size: 10
      minimum-idle: 2
    data:
        - file:../data.sql
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
  

When I change the application implementing something like this: Spring Security hasPermission for Collection<Object>当我更改实现类似这样的应用程序时: Spring Security hasPermission for Collection<Object>

The sql script is not executed. sql 脚本未执行。

I found out that the the issue starts with this code:我发现问题始于以下代码:

@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Autowired
    private PermissionEvaluator permissionEvaluator;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler =
                new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(permissionEvaluator);
        // Pay attention here, or Spring will not be able to resolve bean
        expressionHandler.setApplicationContext(applicationContext);
        return expressionHandler;
    }
}

Then injection of PermissionEvaluator triggers the injection of a number of cascading dependencies.然后PermissionEvaluator的注入触发了许多级联依赖项的注入。 The last component in the chain has 2 dependencies.链中的最后一个组件有 2 个依赖项。 When any of the two is injected data.sql is not executed.当两者中的任何一个被注入data.sql不会执行。

If I remove both dependencies, data.sql is correctly executed.如果我删除这两个依赖项, data.sql将正确执行。

From what I can see ScriptUtils is not picking up the files somehow.据我所知, ScriptUtils并没有以某种方式获取文件。 I wonder how could the two things related.我想知道这两件事怎么可能相关。

I managed to solve by breaking circular dependencies in Bean injection which seems to cause this issue.我设法通过打破 Bean 注入中的循环依赖关系来解决,这似乎导致了这个问题。

Something around these lines:这些线周围的东西:

@Component
class MyPermissionEvaluator implement PermissionEvaluator 
{
  @Autowired
  ObjectFactory<MyPermissionEvaluator> factory;

  public MyPermissionEvaluator {
     return factory.getObject();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM