gpt4 book ai didi

java - Spring Boot 应用程序无法实例化类,除非使用 Autowired 注解

转载 作者:行者123 更新时间:2023-12-02 01:40:42 26 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,它有一个工厂类,用于根据字符串确定要实例化的策略。策略工厂类有 3 个构造函数。每个策略对应一个。这是该类的通用版本:

public class StrategyFactory {
private Strategy1 strategy1;
private Strategy2 strategy2;
private Strategy3 strategy3;

@Autowired
public StrategyFactory(Strategy1 strategy1) {
this.strategy1 = strategy1;
}

public StrategyFactory(Strategy2 strategy2) {
this.strategy2 = strategy2;
}

public StrategyFactory(Strategy3 strategy3) {
this.strategy3 = strategy3;
}

public GenericStrategy getTrailerStrategy(String strategy) {
LOGGER.info("Retrieving Strategy Class for {}", strategy);
if (strategy.equals("CLOSE_DETAIL")) {
return strategy1;
}
else if(strategy.equals("LOAD_TRAILER")) {
return strategy2;
}
else if(strategy.equals("CLOSE_SUMMARY")) {
return strategy3;
}
else {
throw new InvalidStrategyTypeException("Invalid Strategy Type");
}
}
}

当尝试实例化其中一种策略时,只有 @Autowired 策略才会被实例化。如果我尝试实例化其他的,它会返回 null。

如何实例化其他策略?

最佳答案

因为只有用 @Autowired 注解的构造函数才会被处理并注入(inject)依赖项。 Strategy2Strategy3 的构造函数将被忽略,因为上面没有 @Autowired

您有两个选择:

(1) 更改为使用字段注入(inject)而不是构造函数注入(inject):

public class StrategyFactory {
@Autowired
private Strategy1 strategy1;
@Autowired
private Strategy2 strategy2;
@Autowired
private Strategy3 strategy3;

StrategyFactory(){}
}

(2) 继续使用构造函数注入(inject)。由于所有策略都是 GenericStrategy ,因此您可以在构造函数中自动连接 GenericStrategy 列表。然后检查其类以返回实际实例。

代码如下所示:

public class StrategyFactory {
private List<GenericStrategy> strategy;

@Autowired
public StrategyFactory(List<GenericStrategy> strategy) {
this.strategy = strategy1;
}

public GenericStrategy getTrailerStrategy(String strategy) {
LOGGER.info("Retrieving Strategy Class for {}", strategy);
GenericStrategy result = null;
if (strategy.equals("CLOSE_DETAIL")) {
result = getStrategy(Strategy1.class);
}
else if(strategy.equals("LOAD_TRAILER")) {
result = getStrategy(Strategy2.class);
}
else if(strategy.equals("CLOSE_SUMMARY")) {
result = getStrategy(Strategy3.class);
}
else {
throw new InvalidStrategyTypeException("Invalid Strategy Type");
}

if(result == null){
throw new RuntimeException("Fail to load the strategy....");
}
}

private <T> GenericStrategy getStrategy(Class<T> clazz){
for(GenericStrategy s : strategy){
if(clazz.isInstance(s)){
return s;
}
}
return null;
}
}

关于java - Spring Boot 应用程序无法实例化类,除非使用 Autowired 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54468324/

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