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

Spring boot 通过Spring中的注释将参数注入构造函数,spring-boot,spring-annotations,Spring Boot,Spring Annotations,我正在使用Spring引导注释配置。我有一个类,它的构造函数接受2个参数(string,另一个类) Fruit.java 公共类水果{ 公共水果(串果型,苹果){ this.furtype=果型; 这个苹果=苹果; } } Apple.java 公共类苹果{ } 我有一个类需要通过向构造函数注入参数来自动连接上述类(“铁水果”,Apple类) Cook.java 公共类厨师{ @自动连线 水果苹果柚; } cook类需要使用参数自动连接水果类(“铁水果”,苹果类) XML配置如下所示:

我正在使用Spring引导注释配置。我有一个类,它的构造函数接受2个参数(string,另一个类)

Fruit.java

公共类水果{
公共水果(串果型,苹果){
this.furtype=果型;
这个苹果=苹果;
}
}
Apple.java

公共类苹果{
}
我有一个类需要通过向构造函数注入参数来自动连接上述类(“铁水果”,Apple类)

Cook.java

公共类厨师{
@自动连线
水果苹果柚;
}
cook类需要使用参数自动连接水果类(“铁水果”,苹果类)

XML配置如下所示:



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

Apple必须是spring管理的bean:

@Component
public class Apple{

}
还有水果:

@Component
public class Fruit {

    @Autowired
    public Fruit(
        @Value("iron Fruit") String FruitType,
        Apple apple
        ) {
            this.FruitType = FruitType;
            this.apple = apple;
        }
}
注意
@Autowired
@Value
注释的用法

Cook也应该有
@组件

更新

或者您可以使用
@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());
    }
    ...
}

我的问题改进了一点。如果我需要注射不同的苹果(红苹果或绿苹果),该怎么做。同一类的不同bean。水果类构造函数参数必须注入redapple或greenapple如果苹果不是spring管理的,并且来自无法修改的第三方库,那么您可以使用\@Configuration和\@Bean annotationsHow?记住,对Apple类的任何更改都是不受限制的。您的第二个示例是否有问题?通过在appleCook方法中调用redApple(),您将不会得到全局SpringBean“redApple”,而是将创建一个新实例。。。