我正在春季启动中开发Web项目。我正在使用hibernate jpa和spring security。我需要在使用某些服务启动Spring启动应用程序时创建一些用户。我尝试使用@PostConstruct
注释,但它没有将数据插入db。
@Component
public class Monitor {
@Autowired private UserService service
@PostConstruct
public void init(){
if(!service.findBySsoId('admin')) {
service.save(new User(ssoId: 'admin',
lastName: 'amdmin',
firstName: 'admin',
contactNumber: '9999999999',
password: '11changeme',
address2: '',
address1: '',
city: ''
),[UserProfileType.ADMIN,UserProfileType.USER,UserProfileType.DBA])
}
}
}
在grails
我已经通过在bootstrap.groovy
中添加它来完成此操作,在春季启动时我该怎么做?
答案 0 :(得分:3)
查看代码时,我无法理解为什么必须使用Java代码完成用户创建。 Spring Boot有一个特殊的功能叫做#34;数据库初始化"这将是实现你想要的一个很好的方式。
您可以添加包含用SQL编写的必要逻辑的文件data.sql(或data- {platform} .sql)。可以使用Spring Boot的集成测试功能(@IntegrationTest)轻松测试此部分。
答案 1 :(得分:2)
不是要监听bean创建事件(@PostConstruct),而是要在上下文或应用程序启动时监听
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html
@Component
public class SeedDataService {
@EventListener
public void handleContextRefresh(ContextStartedEvent event) {
//Update the records in the DB
}
}
您可以在较新版本的启动中使用ApplicationStartedEvent或 ContextStartedEvent
我认为您遇到了这个问题,因为创建bean时不会创建所有依赖项;有些还在建设中。这些可能不是你的bean的依赖关系,而是阻止SpringApplication将自己视为已开始的依赖关系。
答案 2 :(得分:1)
说实话,如果您一直想在启动时插入这些数据,而不仅仅是出于开发目的,那么您可能会找到更好的解决方案。但是我通常只是实现CommandLineRunner
来快速填充一些有用的对象,然后在开发其他组件以进行一些初步测试时将它们保存到我的数据库中。这样,当我知道我将要删除稍后将要实现的许多逻辑时(因为这会花费更多时间),就不必创建控制器方法来执行相同的操作。例如:
@SpringBootApplication
class Application implements CommandLineRunner {
public static void main(String... args){
SpringApplication.run(Application.class, args);
}
@Autowired ObjectRepository repo;
@Override
public static void run(){
Object obj1 = new Object(1, "obj1");
repo.save(obj1);
}
}
该方法的缺点是,可能很难评估run方法中实际运行的是什么,因为它是在调用SpringApplication.run..
之前运行的。首先,您可能需要显式添加@ComponentScan(baseClassPackages="com.app.repository")
之类的内容来注册存储库。
另一方面,如果您正在寻找更永久的东西,则可以使用所需的insert语句创建一个sql文件,并将其添加到类路径中。然后,添加spring.datasource.data=objectinsertions.sql
,它将在启动时自动在该sql文件中执行插入语句。这可能还需要您定义架构,并类似地添加spring.datasource.schema=objectddl.sql
行。这种方法肯定可以在JDBC中使用,但是实际上我不确定是否可以在JPA中使用。