通过Spring中的注释将构造函数注入到构造函数中

vis*_*har 14 spring-annotations spring-boot

我正在使用Spring Boot注释配置.我有一个类,其构造函数接受2个参数(字符串,另一个类).

Fruit.java

public class Fruit {
    public Fruit(String FruitType, Apple apple) {
            this.FruitType = FruitType;
            this.apple = apple;
        }
}
Run Code Online (Sandbox Code Playgroud)

Apple.java

public class Apple {

}
Run Code Online (Sandbox Code Playgroud)

我有一个类需要通过向构造函数注入参数来自动装配上面的类("iron Fruit",Apple类)

Cook.java

public class Cook {

    @Autowired
    Fruit applefruit;
}
Run Code Online (Sandbox Code Playgroud)

厨师课需要使用参数自动装配Fruit类("铁水果",Apple类)

XML配置如下所示:

<bean id="redapple" class="Apple" />
<bean id="greenapple" class="Apple" />
<bean name="appleCook" class="Cook">
          <constructor-arg index="0" value="iron Fruit"/>
          <constructor-arg index="1" ref="redapple"/>
</bean>
<bean name="appleCook2" class="Cook">
          <constructor-arg index="0" value="iron Fruit"/>
          <constructor-arg index="1" ref="greenapple"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

如何仅使用注释配置来实现它?

med*_*088 14

Apple必须是一个Spring管理的bean:

@Component
public class Apple{

}
Run Code Online (Sandbox Code Playgroud)

水果也是:

@Component
public class Fruit {

    @Autowired
    public Fruit(
        @Value("iron Fruit") String FruitType,
        Apple apple
        ) {
            this.FruitType = FruitType;
            this.apple = apple;
        }
}
Run Code Online (Sandbox Code Playgroud)

请注意@Autowired@Value注释的用法.

库克也应该有@Component.

更新

或者您可以使用@Configuration@Bean注释:

@Configuration 
public class Config {

    @Bean(name = "redapple")
    public Apple redApple() {
        return new Apple();
    }

    @Bean(name = "greeapple")
    public Apple greenApple() {
        retturn new Apple();
    }

    @Bean(name = "appleCook")
    public Cook appleCook() {
        return new Cook("iron Fruit", redApple());
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)