springboot整合数据源初始化
时间: 2023-09-06 10:07:15 浏览: 43
在Spring Boot中,可以使用application.yml或application.properties文件来配置数据源。其中,application.yml是使用YAML语言编写的配置文件,而application.properties则是使用键值对的形式编写的配置文件。
下面是使用application.yml来配置数据源的示例:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
driver-class-name: com.mysql.jdbc.Driver
```
其中,url、username、password和driver-class-name四个属性分别表示数据源的连接地址、用户名、密码和驱动类名。
如果需要在应用程序启动时初始化数据,可以使用Spring Boot提供的ApplicationRunner或CommandLineRunner接口。这两个接口都只有一个run方法,可以在其中编写初始化数据的代码。
下面是使用ApplicationRunner接口初始化数据的示例:
```
@Component
public class DataLoader implements ApplicationRunner {
@Autowired
private UserRepository userRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
User user1 = new User("John", "Doe");
User user2 = new User("Jane", "Doe");
userRepository.save(user1);
userRepository.save(user2);
}
}
```
在上面的示例中,使用@Autowired注解注入了一个UserRepository对象,并在run方法中向数据库中插入了两条用户记录。
需要注意的是,ApplicationRunner和CommandLineRunner接口都是在Spring Boot应用程序启动完成后执行的,因此如果需要在应用程序启动前执行初始化操作,可以考虑使用Spring Boot提供的ApplicationListener接口。