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

前端 未结 2 2252
没有蜡笔的小新
没有蜡笔的小新 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:32

    I'm not entirely certain that this question is a dupe, (only 90% sure), but this answer:

    https://stackoverflow.com/a/13243066/1768232

    Seems to have the information you need. Specifically, you should do this:

    I got it working by fetching an instance of the bean used in the constructor-arg out of the context and then populating it with the values that you are working with at run-time. This bean will then be used as the parameter when you get your factory-generated bean.

    public class X {
       public void callFactoryAndGetNewInstance() {
          User user = context.getBean("user");
          user.setSomethingUsefull(...);
          FileValidator validator = (FileValidator)context.getBean("fileValidator");
          ...
       }
    }
    

    I recommend reading the entire answer.

    0 讨论(0)
  • 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);
                }
            };
        }
    }
    
    0 讨论(0)
提交回复
热议问题