[英]Autopopulate Database with Spring Boot
我有一个使用大量预填充表的 Spring 引导应用程序。 这些表的内容可以在实例之间改变。 我目前使用以下代码从 JSON 文件加载表:
@Configuration
public class PreLoader {
@Bean
@Conditional(PreloadCondition.class)
Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulatorNameType() {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
final Logger log = LoggerFactory.getLogger(Jackson2RepositoryPopulatorFactoryBean.class);
Resource[] resources = null;
try {
resources = new PathMatchingResourcePatternResolver().getResources("classpath*:*-data.json");
log.debug("Found {} resources for preloading:", resources.length);
for (Resource resource : resources) {
log.debug(resource.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
factory.setResources(resources);
return factory;
}
}
如何修改此代码以仅在数据库初始化时运行? 我尝试使用@Conditional,如下所示:
@Configurable
public class PreloadCondition implements Condition {
@PersistenceContext
private EntityManager entityManager;
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return tableExistsService.exists("identity_use");
}
static boolean tableExistsSQL(Connection connection, String tableName) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) "
+ "FROM information_schema.tables "
+ "WHERE table_name = ?"
+ "LIMIT 1;");
preparedStatement.setString(1, tableName);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getInt(1) != 0;
}
}
但是, entityManager 是 null - 可能是因为 class 不是“弹簧管理”? @Configurable 似乎没有帮助?
作为参考,以防其他人偶然发现这个问题。 我决定使用不同的条件来解决这个问题。 代码块如下。 注 1)“条件”数据是从 application.properties 中读取的,2)可以加载多个资源文件。 希望这对某人有帮助!
@Configuration
@ConditionalOnProperty(
prefix = "myappname",
name = "initialize",
havingValue = "true",
matchIfMissing = false)
public class PreLoader {
@Bean
Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulatorNameType() {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
final Logger log = LoggerFactory.getLogger(Jackson2RepositoryPopulatorFactoryBean.class);
Resource[] resources = null;
try {
resources = new PathMatchingResourcePatternResolver().getResources("classpath*:*-data.json");
log.debug("Found {} resources for preloading:", resources.length);
for (Resource resource : resources) {
log.debug(resource.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
factory.setResources(resources);
return factory;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.