【问题标题】:How to use @Postconstruct in order to load some data如何使用@Postconstruct 加载一些数据
【发布时间】:2019-01-14 19:06:01
【问题描述】:

目前,我有一个 import.sql,我可以使用它在我的数据库中导入一些测试数据。现在,我想把它带到我们的生产系统中,到目前为止我读到的是我不应该在生产中使用 import.sql。

因此,我认为我可以使用@Postconstruct 创建一些东西。

因此,我在主应用程序类中创建了类似的东西:

@Autowired
ICreateUserAtStartup repo;

@PostConstruct
public void initIt() throws Exception {
    Rolle r = new Rolle();
    r.setBezeichnung("xxx");
    r.setId(1L);
    r.setCreatedAt(new Date(2019, 01, 14));

    repo.insertRolle(1L, "xxx");   
}

在一个单独的文件中,我创建了以下界面:

@Repository
public interface ICreateUserAtStartup {

    @Modifying
    @Query("insert into benutzer(id, created_at, anzeigename, 
    benutzername, dienstnummer, active, passwort) SELECT :id, 
    :created_At, :anzeigename, :benutzername, :dienstnummer, :active, 
    :passwort")

    void insertBenutzer(@Param("id") Long id, @Param("created_at") 
    String created_at, @Param("anzeigename") String anzeigename, 
    String benutzername, String dienstnummer, Boolean active, String password);

    @Modifying
    @Query("insert into rolle(id, bezeichnung) SELECT (:id, 
    :bezeichnung)")
    void insertRolle(@Param("id") Long id, @Param("bezeichnung") 
    String bezeichnung);
}

但是,一旦我尝试在我的主类中自动装配 repo,我总是会遇到以下异常:

没有可用的“x.y.z.repository.ICreateUserAtStartup”类型的合格 bean

【问题讨论】:

标签: spring-boot postconstruct


【解决方案1】:

您为什么不为此使用特定的迁移工具,例如 Flyway 或 Liquibase?

https://flywaydb.org/

https://www.liquibase.org/

它不能自动装配的原因是你还没有实现那个接口并从实现中创建了一个 bean。当然你可能会认为,如果你只是创建一个接口并使用@Repository 对其进行注释,它会开箱即用,但事实并非如此。

如果您想将 Spring Data 用于您的存储库层,您将需要一个实体并且您至少需要扩展 CrudRepository

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多