java - 需要实例化的类的 Spring @Autowire 属性

标签 java spring spring-boot

public class Player {
   @Autowired gameService

   @Getter @Setter String name;

   public Player(String name) {
      this.name = name
   }

   public doSomething() {
      gameService.something() // gameService is null!
   }

}
@Service 
class GameService { public void something() {...} }

如果我要执行 new Player("John").doSomething() java 会提示 this.gameService 为空。需要实例化播放器类。

是否可以让 gameService 正确地自动连接到服务?

最佳答案

If I were to do new Player("John").doSomething()

当你自己创建java实例时,这个实例对于Spring框架是未知的。所以 Spring 不会用它包含的任何依赖项来丰富它。

为了让您的类通过@Autowired 包含依赖项,您必须让spring 创建这个实例。实际上,Spring 将为您提供的类创建一个代理,而不是您编写的实际类。实现这一点的一种方法是用 @Component 标记您的类 Player,然后您还必须从 Spring 框架中检索实例播放器以正确包含它的依赖项。

请记住,默认情况下 @Comopnent Player 将成为 spring 的单例,这与我认为您希望此类的逻辑用途不完全匹配。要么你希望它成为一个 prototype 或者更好我认为你必须将 gameService 的使用移到 Player 类之外。

可能您可以在 GameService 中使用 something() 方法,将 Player 作为参数并执行相同的操作。然后你可以在 gameService 的任何地方 Autowiring ,这听起来应该是一个单例。

关于java - 需要实例化的类的 Spring @Autowire 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71777476/

相关文章:

java - Spring 4.0.6 与 quartz 1.8.6 : setCronExpression method is not exposed to CronTriggerBean class

java - Spring boot 端点参数签名,在给定两个参数时抛出不明确的端点异常

spring - Spring Boot 应用程序中的 H2 架构为空

java - 如何捕获ResponseEntityExceptionHandler的响应来创建JWE加密

java - 找不到主类,IntelliJ 正在构建一个 jar

java - JAX-RS 将 HashMap 转换为 XML 或 JSON

java - 如何在 Spring Boot @Async 中使用 ForkJoinPool?

java - 如何从 CSV header 创建 pojo 类

java - `java -cp` 只是 `java -classpath` 的缩写吗?

java - 简单的 JNDI 上下文工厂?