What is the Spring Framework equivalent to FactoryModuleBuilder, @AssistedInject, and @Assisted in Google Guice? In other words, what is the recommended approach using Spring t
Spring has no equivalent to the Guice FactoryModuleBuilder
. The closest equivalent would be a Spring @Configuration
class that provides a factory bean that implements a factory interface whose methods accept arbitrary arguments from the application. The Spring container could inject dependencies into the @Configuration
object that it, in turn, could supply to the factory constructor. Unlike with FactoryModuleBuilder
, the Spring approach produces a lot of boilerplate code typical of factory implementations.
Example:
public class Vehicle {
}
public class Car extends Vehicle {
private final int numberOfPassengers;
public Car(int numberOfPassengers) {
this.numberOfPassengers = numberOfPassengers;
}
}
public interface VehicleFactory {
Vehicle createPassengerVehicle(int numberOfPassengers);
}
@Configuration
public class CarFactoryConfiguration {
@Bean
VehicleFactory carFactory() {
return new VehicleFactory() {
@Override
Vehicle createPassengerVehicle(int numberOfPassengers) {
return new Car(numberOfPassengers);
}
};
}
}