我正在使用Guice实现的项目,但是我们需要将它迁移到Spring 3.x,我们在下面有这个用例,其中bean需要额外的参数来创建。这是如何在Spring中实现的?是否可以仅使用注释(并且没有xml)来实现?
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.assistedinject.Assisted;
import javax.inject.Inject;
public class MyModule extends AbstractModule {
@Override
protected void configure() {
super.binder().install(new FactoryModuleBuilder().
implement(Car.class, CarImpl.class).
build(CarFactory.class));
}
}
public interface Car {
String getBrand();
String getModel();
}
public class CarImpl implements Car {
public CarImpl(@Assisted("brand") String brand, @Assisted("model") String model) {
this.brand = brand;
this.model = model;
}
@Override
String getBrand() { return brand; }
@Override
String getModel() { return model; }
private final String brand;
private final String model;
}
public interface CarFactory {
Car create(@Assisted("brand") String brand, @Assisted("model") String model);
}
public class Client {
@Inject CarFactory carFactory;
final Car myCar;
public Client() {
myCar = carFactory.create("BMW", "530d xDrive");
}
void driveIt() { /* don't crash it */ }
public static void main(String[] args) {
new Client().driveIt();
}
}
答案 0 :(得分:2)
看起来你只需要一个返回CarImpl的工厂bean。
laravel-elixir-jade