|
1 | 1 | package com.example.solidconnection.support; |
2 | 2 |
|
3 | | -import jakarta.annotation.PostConstruct; |
4 | | -import org.springframework.boot.jdbc.DataSourceBuilder; |
5 | | -import org.springframework.boot.test.context.TestConfiguration; |
6 | | -import org.springframework.context.annotation.Bean; |
| 3 | +import org.springframework.boot.test.util.TestPropertyValues; |
| 4 | +import org.springframework.context.ApplicationContextInitializer; |
| 5 | +import org.springframework.context.ConfigurableApplicationContext; |
7 | 6 | import org.testcontainers.containers.MySQLContainer; |
8 | | -import org.testcontainers.junit.jupiter.Container; |
9 | 7 |
|
10 | | -import javax.sql.DataSource; |
| 8 | +public class MySQLTestContainer implements ApplicationContextInitializer<ConfigurableApplicationContext> { |
11 | 9 |
|
12 | | -@TestConfiguration |
13 | | -public class MySQLTestContainer { |
14 | | - |
15 | | - @Container |
16 | 10 | private static final MySQLContainer<?> CONTAINER = new MySQLContainer<>("mysql:8.0"); |
17 | 11 |
|
18 | | - @Bean |
19 | | - public DataSource dataSource() { |
20 | | - return DataSourceBuilder.create() |
21 | | - .url(CONTAINER.getJdbcUrl()) |
22 | | - .username(CONTAINER.getUsername()) |
23 | | - .password(CONTAINER.getPassword()) |
24 | | - .driverClassName(CONTAINER.getDriverClassName()) |
25 | | - .build(); |
| 12 | + static { |
| 13 | + CONTAINER.start(); |
26 | 14 | } |
27 | 15 |
|
28 | | - @PostConstruct |
29 | | - void startContainer() { |
30 | | - if (!CONTAINER.isRunning()) { |
31 | | - CONTAINER.start(); |
32 | | - } |
| 16 | + @Override |
| 17 | + public void initialize(ConfigurableApplicationContext applicationContext) { |
| 18 | + TestPropertyValues.of( |
| 19 | + "spring.datasource.url=" + CONTAINER.getJdbcUrl(), |
| 20 | + "spring.datasource.username=" + CONTAINER.getUsername(), |
| 21 | + "spring.datasource.password=" + CONTAINER.getPassword() |
| 22 | + ).applyTo(applicationContext.getEnvironment()); |
33 | 23 | } |
34 | 24 | } |
0 commit comments