gpt4 book ai didi

spring-boot - Spring中通过注解向构造函数注入(inject)参数

转载 作者:行者123 更新时间:2023-12-03 22:23:14 25 4
gpt4 key购买 nike

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

水果.java

public class Fruit {
public Fruit(String FruitType, Apple apple) {
this.FruitType = FruitType;
this.apple = apple;
}
}

苹果.java

public class Apple {

}

我有一个类需要通过向构造函数注入(inject)参数来 Autowiring 上述类(“iron Fruit”,Apple 类)

库克.java

public class Cook {

@Autowired
Fruit applefruit;
}

厨师类需要 Autowiring 带有参数的水果类(“铁水果”,苹果类)

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>

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

最佳答案

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注释。

库克应该有 @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());
}
...
}

关于spring-boot - Spring中通过注解向构造函数注入(inject)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com