This project is based on chapter 2.2.3. Programmatically adding beans to the Spring context from book Spring Starts here (2021) by Laurentiu Spilca.
File > New project > Java
public class Book {
private final String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Book book = (Book) obj;
return title == book.title || (title != null && title.equals(book.title));
}
public int hashCode() {
return title == null ? 0 : title.hashCode();
}
}
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.10</version>
</dependency>
ApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(Book.class, "The Hunger Games");
context.refresh();
System.out.println("The book's title is " + context.getBean(Book.class).getTitle());
<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);
}
}
public class BookTests {
@Test
@DisplayName("Checks that Book is added to the context")
public void checkBookAddedToContext() {
GenericApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(Book.class, "The Hunger Games");
context.refresh();
Book book = context.getBean(Book.class);
assertEquals(new Book("The Hunger Games"), book);
}
}