Skip to content

@ServiceConnection annotation causes early bean initialization #35168

@quaff

Description

@quaff
import static org.assertj.core.api.Assertions.assertThat;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.MySQLContainer;

import com.zaxxer.hikari.HikariDataSource;

@SpringBootTest
public class ApplicationTests {

	@Autowired
	private DataSource dataSource;

	@Test
	void test() {
		assertThat(dataSource).isInstanceOfSatisfying(HikariDataSource.class,
				ds -> assertThat(ds.getJdbcUrl()).startsWith("jdbc:mysql://"));
	}

	@TestConfiguration
	static class Config {

		@Autowired
		Environment env;

		@Bean
		@ServiceConnection
		GenericContainer<?> mysql() {
			assertThat(env).isNotNull(); // assertion failed
			return new MySQLContainer<>("mysql:5.7");
		}
	}
}

Inject Environment env by method parameter instead works fine.
Remove @ServiceConnection will make field injection works fine but dataSource not wanted.

Metadata

Metadata

Assignees

Labels

theme: containersTestcontainers, Docker Compose and Buildpack featurestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions