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

你离开我真会死。 提交于 2019-12-04 01:54:37

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!