What is the Spring equivalent to FactoryModuleBuilder, @AssistedInject, and @Assisted in Guice?

前端 未结 2 2227
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 04:12

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

2条回答
  •  执笔经年
    2021-02-20 04:42

    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);
                }
            };
        }
    }
    

提交回复
热议问题