Stage 12: Create beans with explicit factory methods
Learning path / Stage 12 of 37
mvn spring-boot:run. Use the port specified for this stage and stop with Ctrl+C.Download spring-products-bean-config.zip · Complete file-by-file guide
Start simply: what are we learning?
Stage 12 teaches another way to give Spring an object to manage. Earlier we marked our classes with @Component, @Service or @Controller. Here we also write @Bean methods that return objects for Spring to manage. The returned object is the bean; the method producing it is the factory method.
What is the business meaning of catalog?
Catalog means our collection of products. It is a business name we chose, not a Spring keyword. Imagine a shop displaying prices in INR and offering a well-stocked-products page that includes only products with at least 20 items available.
CatalogSettings settings = new CatalogSettings("INR", 20);CatalogSettings holds these choices. ProductService uses minimumStock to choose products; the controller supplies the settings to the page for display. CatalogConfig specifies how the settings object is constructed. Separating those responsibilities is separation of concerns. A separate settings class is optional for this small application; we chose it as a concrete example of configuring an object with values.
| Name | What it means here |
|---|---|
| CatalogSettings | The ordinary Java class holding currency and minimumStock. |
| CatalogConfig | The configuration class containing our factory methods. |
| Factory method | A method that produces and returns an object reference. |
| Bean | The actual object managed by Spring. Bean does not mean separation of concerns. |
Is there a disadvantage to @Component on ProductFileReader?
There is no problem with @Component here. Stage 12 still uses it on ProductFileReader. What changes is where its JsonMapper helper comes from. Earlier, the reader built a mapper inside its constructor. Now, it asks for one through its constructor and Spring supplies the configured mapper bean.
@Bean
public JsonMapper jsonMapper() {
return JsonMapper.builder().build();
}JsonMapper is a library class. We cannot edit that dependency class in our project to put @Component on it. An @Bean method lets us build its object and give it to Spring. @Component suits classes we own and want Spring to discover; @Bean suits explicit construction, including objects from libraries. Neither approach is a replacement for the other.
Can we share a JsonMapper without Spring?
Yes. Spring is not required to create an object once and share its reference. The following illustrative statements use the Stage 12 ProductFileReader constructor. They demonstrate ordinary Java, not additional application startup code:
JsonMapper mapper = JsonMapper.builder().build();
ProductFileReader firstReader = new ProductFileReader(mapper);
ProductFileReader secondReader = new ProductFileReader(mapper);There are two reader objects but both receive the same mapper object. By contrast, independently calling JsonMapper.builder().build() twice creates two mapper objects. Manually sharing one instance is possible; it does not itself enforce the singleton design pattern.
With @Bean, Spring manages the sharing for us. Its default singleton scope means one instance for that bean definition in that application context. It does not mean that Java prevents other mapper objects from being created. Calling the builder yourself still creates a separate object.
What does @Component actually tell Spring?
@Component marks a class for discovery by component scanning. When that class is discovered and registered, Spring creates and manages its object and resolves the required dependencies. In our example, read the startup sequence as:
- Spring discovers ProductFileReader in the scanned application package.
- It sees that the reader constructor requires a JsonMapper.
- It obtains the mapper bean from the configured factory method.
- It calls the reader constructor with that mapper reference.
- It keeps the reader bean available for other beans that need it.
@Component does not create every object the application might ever need. Each required dependency must be available through component discovery, explicit configuration or another Spring registration mechanism. Spring reports a startup error if it cannot resolve a required dependency.
Our default, non-lazy singleton beans are created during application-context startup. Spring also supports deferred creation and other scopes, so not every possible object must be created at startup. We do not need those additional features to understand this stage.
Say it in your own words: I can create and share objects myself. Spring can take responsibility for creating, managing and supplying the objects I register. @Component and @Bean are two ways of telling Spring about those objects.
Use a standalone file-based example
This stage builds on Stage 10 so you can focus on bean configuration without starting MongoDB. It runs on 8090 and retains the original getInputStream() and try-with-resources reading method.
Separate a class from its managed object
CatalogSettings is an ordinary class with currency and minimumStock fields. It has no @Component annotation. new CatalogSettings("INR", 20) creates an ordinary Java object. Returning that object from an @Bean method lets Spring register and manage that particular object as a bean.
Read the factory methods
CatalogConfig has @Configuration. Its jsonMapper() method builds and returns a library JsonMapper. Its catalogSettings() method constructs and returns our settings object. A factory method is simply a method whose job is to produce an object. Here @Bean tells Spring to call these methods and register their returned objects. The default bean names are the method names.
Inject the results
ProductFileReader asks for JsonMapper in its constructor instead of building its own mapper. ProductService asks for CatalogSettings and uses minimumStock as the filtering threshold. The controller adds settings to Model so the page can show INR and 20. These are references to the managed objects, not copies of their source classes.
Change one setting and observe the rule
All products shows 30 rows. The policy link selects products whose stock is at least 20, including exactly 20. Change the factory’s minimumStock from 20 to 30, restart and compare the filtered page. A code change takes effect after rebuilding/restarting.
Inspect the registry and scope
Open /bean-info. The page checks bean definitions for jsonMapper, catalogSettings, productFileReader, fileProductRepository, productService and productController. A bean definition is the container’s registration information; a bean is the actual object. The registry keeps these named definitions. Two context lookups of catalogSettings return the same object because its default scope is singleton.
Avoid accidental extra objects
@Configuration(proxyBeanMethods=false) is used here. Calling a factory method directly in ordinary Java would be an ordinary method call. This example obtains the managed objects through constructor injection and context lookup, rather than calling one factory method from another.
Run this stage
Use JDK 21+ and Maven 3.9+. Extract spring-products-bean-config.zip and open a terminal in the spring-products-bean-config folder containing pom.xml. Keep the source files in their supplied paths.
mvn spring-boot:runOpen http://localhost:8090/products. Keep the terminal open. Stop with Ctrl+C. If the port is occupied, change server.port in src/main/resources/application.properties, restart and use the new port in the browser.
# Choose another available port if this port is busy.
server.port=8090
Expected output and checks
Open /products and confirm currency INR and minimum stock 20. Use the policy link. Open /bean-info: all six registrations and singleton checks are true, and the two settings lookups are identical. Stop the app and change the threshold to 30 for the exercise.
Read the changed Java files
The downloadable project includes every file, the 30-product text file, templates, CSS, pom.xml and a standalone README.html with all source files. These are the key changes from the preceding example.
src/main/java/com/edupoly/products/CatalogConfig.java
package com.edupoly.products;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tools.jackson.databind.json.JsonMapper;
@Configuration(proxyBeanMethods = false)
public class CatalogConfig {
@Bean
public JsonMapper jsonMapper() {
return JsonMapper.builder().build();
}
@Bean
public CatalogSettings catalogSettings() {
return new CatalogSettings("INR", 20);
}
}
src/main/java/com/edupoly/products/CatalogSettings.java
package com.edupoly.products;
public class CatalogSettings {
private final String currency;
private final int minimumStock;
public CatalogSettings(String currency, int minimumStock) {
this.currency = currency;
this.minimumStock = minimumStock;
}
public String getCurrency() { return currency; }
public int getMinimumStock() { return minimumStock; }
}
src/main/java/com/edupoly/products/ProductFileReader.java
package com.edupoly.products;
import java.io.IOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
@Component
public class ProductFileReader {
private final Product[] products;
public ProductFileReader(JsonMapper mapper) throws IOException {
var resource = new ClassPathResource("data/products.txt");
try (var input = resource.getInputStream()) {
products = mapper.readValue(input, Product[].class);
}
System.out.println("Created ProductFileReader");
}
public Product[] getProducts() {
return products;
}
}
src/main/java/com/edupoly/products/ProductService.java
package com.edupoly.products;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductRepository repository;
private final CatalogSettings settings;
public ProductService(ProductRepository repository, CatalogSettings settings) {
this.repository = repository;
this.settings = settings;
}
public List<Product> findAll(boolean inStockOnly) {
List<Product> selected = new ArrayList<>();
for (Product product : repository.findAll()) {
if (!inStockOnly || product.getStock() >= settings.getMinimumStock()) {
selected.add(product);
}
}
return selected;
}
public Optional<Product> findById(int id) {
return repository.findById(id);
}
}
src/main/java/com/edupoly/products/BeanInfoController.java
package com.edupoly.products;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class BeanInfoController {
private final ConfigurableApplicationContext context;
public BeanInfoController(ConfigurableApplicationContext context) {
this.context = context;
}
@GetMapping(value = "/bean-info", produces = "text/plain")
@ResponseBody
public String beanInfo() {
StringBuilder text = new StringBuilder();
for (String name : new String[] {"jsonMapper", "catalogSettings", "productFileReader",
"fileProductRepository", "productService", "productController"}) {
text.append(name)
.append(" | definition registered: ").append(context.containsBeanDefinition(name))
.append(" | singleton: ").append(context.isSingleton(name)).append("\n");
}
text.append("Same settings bean on two lookups: ")
.append(context.getBean(CatalogSettings.class) == context.getBean(CatalogSettings.class));
return text.toString();
}
}
Practice
Change minimumStock from 20 to 30, restart and compare the filtered list. Explain why CatalogSettings is a bean even though its class has no @Component.
References: Spring constructor injection, Spring Data MongoDB repositories.
Follow the factory method in concrete steps
1. Spring reads CatalogConfig. 2. Spring calls its @Bean factory method with the dependencies it needs. 3. The Java statements in that method create or configure the object. 4. The method returns that object to Spring. 5. Spring manages it as a bean and supplies it where requested. CatalogSettings is a separate settings object, not the container. A library mapper can be registered this way without changing the library class to add @Component. Using new inside a factory method does not create a new mapper on every service call; the bean definition has singleton scope by default.
After Stage 12: the Spring words to recognize
| Term | Our concrete example | Its place in Spring |
|---|---|---|
| @Configuration | CatalogConfig | Declares a class containing explicit bean configuration. |
| @Bean and factory method | catalogSettings() returns new CatalogSettings(...) | Spring registers the object returned by this method. |
| Bean definition / registry | The named catalogSettings registration | The container keeps information describing how to obtain a managed object. |
| Singleton — observed again | Two lookups return the same settings reference | One instance for this bean definition in this context by default. |
One small check: Point to the class, constructor or annotation that demonstrates each term before continuing.
Concepts used in this stage
Use the right column for a quick reminder, or open a concept above for its full explanation.