A simple Spring Core (Java-based configuration) project demonstrating the use of FactoryBean to dynamically create different types of engine objects (Diesel, Electric, Hybrid) based on external configuration.
This project showcases how to:
- Use Spring's
FactoryBeaninterface to control object creation. - Externalize configuration using
application.properties. - Achieve loose coupling via interfaces and dependency injection.
- Dynamically switch implementations without changing code.
- Java
- Spring Core (Annotation-based configuration)
- Maven (optional, if you add build support)
com.nit
│
├── config
│ └── AppConfig.java
│
├── factory
│ └── VehicleEngineFactoryBean.java
│
├── sbeans
│ ├── Engine.java
│ ├── DieselEngine.java
│ ├── ElectricEngine.java
│ └── HybridEngine.java
│
└── main
└── TestApp.java
Instead of directly creating objects using new, we let Spring decide which engine to create at runtime using a custom FactoryBean.
-
The engine type is read from properties:
engine.type=diesel -
Based on this value, the factory returns the correct implementation:
if(engineType.equalsIgnoreCase("electric")) {
return new ElectricEngine();
}
else if(engineType.equalsIgnoreCase("diesel")) {
return new DieselEngine();
}
else if(engineType.equalsIgnoreCase("hybrid")) {
return new HybridEngine();
}- Loads properties and configures the FactoryBean
- Central place where object creation logic exists
- Common contract for all engine types
- Diesel Engine →
- Electric Engine →
- Hybrid Engine →
- Bootstraps Spring container and runs the app
-
Clone the repository
-
Open in your IDE (Eclipse / IntelliJ)
-
Set engine type in
application.properties:engine.type=electric -
Run:
TestApp.java
DieselEngine has started.
DieselEngine has stoped.
ElectricEngine has started.
ElectricEngine has stoped.
This pattern is super useful when:
- You want runtime flexibility
- You want to follow SOLID principles
- You need clean separation of object creation logic
- Add Spring Boot support
- Use profiles instead of properties
- Add logging framework (SLF4J / Logback)
- Introduce dependency injection into engines
This project is for educational purposes.
Small project, but the concept? 🔥
Understanding FactoryBean gives you real control over how Spring creates and manages objects — that’s where things start getting powerful.