liveBook · Manning

Spring bean

As explained in Testing Spring Boot Applications

A Spring bean is an object instantiated, configured, and managed by the Spring application context.

A Spring bean is an application component managed by the Spring ApplicationContext. The context connects components and lets application code or tests access them. In a Spring Boot test, the useful question is often which beans should remain as configured and which need test-specific replacements. section 1.3 section 1.4

A typical full-application test handles beans declaratively:

  • Use @SpringBootTest to test the application with test-specific properties. section 1.4
  • Use @Autowired to inject a bean, such as a repository, into the test for actions or assertions. section 1.4
  • Use @MockitoBean to replace a production collaborator that should not run during the test. section 1.4
Listing 1.4 A typical Spring Boot Tests configuration.
@SpringBootTest(properties = "widget.id.step=5") #1
@AutoConfigureMockMvc #2
class AwesomeSpringBootTests {

  @Autowired
  private MockMvc mockMvc; #2

  @Autowired
  private WidgetRepository repository; #3

  @MockitoBean
  private WidgetValidator mockValidator; #4


}

The test configuration injects a repository, replaces a validator with a mock, and makes MockMvc available without manually managing the application context. section 1.4

Direct bean access can make an integration test easier to write: after an HTTP request, an injected repository can check what was stored. It can also couple a behavior test to the data model. For real projects, prefer interacting through services or controllers when that avoids such coupling. section 2.4

How Testing Spring Boot Applications covers it

How deep it goes
Explains context access, field injection, and mock replacement, but does not explore bean lifecycle or container internals.
Examples
Shows an injected repository and mocked validator in a widget test, plus a repository assertion after a city-selection request.
What it assumes
Assumes familiarity with Spring Boot annotations, controllers, and repositories while avoiding manual ApplicationContext setup.
What you can do after
Apply it via @SpringBootTest and @Autowired to access dependencies, and @MockitoBean to replace a collaborator for testing.
How it connects
Connects beans to the ApplicationContext, dependency injection, component scanning, integration testing, and test doubles.

Also explained in

Compare how 5 books explain Spring bean →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.