This project is based on chapter 2.2.2. Using stereotype annotations to add beans to the Spring context from book Spring Starts here (2021) by Laurentiu Spilca.
File > New project > Java
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.10</version>
</dependency>
public class Book {
private final String title;
public Book() {
this.title = "One Hundred Years of Solitude";
}
public String getTitle() {
return title;
}
}
+ @Component
public class Book {
private final String title;
public Book() {
this.title = "One Hundred Years of Solitude";
}
public String getTitle() {
return title;
}
}
@Configuration
public class ApplicationConfiguration {
}
@Configuration
+ @ComponentScan(basePackages = "org.example")
public class ApplicationConfiguration {
}
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
Book book = context.getBean(Book.class);
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>6.1.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.11.0-M2</version>
<scope>test</scope>
</dependency>
public class ApplicationTests {
@Test
@DisplayName("Checks that Application Context is created")
public void checkApplicationContextCreated() {
ApplicationContext context = new AnnotationConfigApplicationContext();
assertNotNull(context);
}
}
- use
@ExtendWith(SpringExtension.class)
to integrate Spring TestContext Framework to the test - use
@ContextConfiguration
to configure Spring context in Spring integration tests
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { ApplicationConfiguration.class })
public class BookTests {
@Autowired
private Book book;
@Test
@DisplayName("Fetch the book bean from the context")
public void fetchBookBean() {
String actualTitle = book.getTitle();
String expectedTitle = "One Hundred Years of Solitude";
assertEquals(actualTitle, expectedTitle);
}
}