Java 构造函数与基元参数自动关联
读过关于构造函数依赖注入是多么棒的文章后,我现在就在玩它。现在让我困惑的是,如果其中一个参数是基元类型,例如Java 构造函数与基元参数自动关联,java,spring,dependency-injection,autowired,Java,Spring,Dependency Injection,Autowired,读过关于构造函数依赖注入是多么棒的文章后,我现在就在玩它。现在让我困惑的是,如果其中一个参数是基元类型,例如 @Component @Scope("prototype") public class Car { private Category category; private Fuel fuel; private String name; @Autowired public Car(String name, Category category, Fuel fuel) { t
@Component
@Scope("prototype")
public class Car {
private Category category;
private Fuel fuel;
private String name;
@Autowired
public Car(String name, Category category, Fuel fuel) {
this.name = name;
this.category = category;
this.fuel = fuel;
}
从主方法调用构造函数:
@Component
public final class Start {
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = AppContext.initAppContext();
// No xml bean definition as class is a component
// car name should be initialized to "toyota"
Car yaris = context.getBean(Car.class);
因此,在上述情况下,我应该返回到字段或setter注入?您通常会使用@Value来注释名称。你想注射什么?名称从何而来?更新我的问题以显示如何调用构造函数,但您希望Spring为
name
参数传递哪个值?任何字符串值,例如“toyota”,因此,您不关心该值?如果不关心值,将字符串作为参数传递有什么意义?