java - Autowired/Dependencies 注入在 Spring Shell 项目中不起作用
问题描述
我从https://www.baeldung.com/spring-shell-cli开始了一个新项目
我试图在我的班级上使用依赖注入或Autowired
注释。BannerProvider
但是 Spring 提出了一个例外。
我的应用程序类 经过多次定制
@SpringBootApplication
public class MyCLIApplication extends Bootstrap {
public static void main(String[] args) {
SpringApplication.exit(SpringApplication.run(MyCLIApplication.class, args));
}
}
我的 BannerProvider 组件
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyBannerProvider extends DefaultBannerProvider {
private final Point screenSize;
public MyBannerProvider(@Qualifier("ScreenSize") Point screenSize) {
this.screenSize = screenSize;
}
[other stuff]
}
我的 POM 依赖项
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>${jline.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
</dependencies>
运行错误
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Qualifier("ScreenSize")
The following candidates were found but could not be injected:
- User-defined bean method 'screenSize' in 'TerminalConfiguration'
Action:
Consider revisiting the entries above or defining a bean of type 'my.namespace.Point' in your configuration.
谢谢你的支持。
解决方案
bean创建中有两个问题:
@Bean @Qualifier("ScreenSize") public Point screenSize() {...}
- @Qualifier 注解不用于创建 bean,它与 @autowired 一起使用以消除当您有多个具有相同类型的 bean 时需要注入哪个 bean 的问题。
- 如果您需要指定bean的名称(id),您应该在这种情况下使用:
@Bean("ScreenSize")
*请注意,如果您没有在@Bean注解中指定bean的名称,默认情况下容器考虑的名称与方法的名称,在您的情况下是“screenSize”。
在您的问题的解决方案下方:
声明你的 Point bean:
@Bean(name="ScreenSize") public Point screenSize() {...}
注入 bean:
@Autowired public MyBannerProvider(@Qualifier("ScreenSize") Point screenSize) { this.screenSize = screenSize; }