Spring - 在 Main 中使用 @Component 注释 class 的正确方法

Spring - proper way to use @Component annotated class in Main

我有我的 TCPServer class 实现 Runnable 并用 @Component 注释。 我有一个 ThreadPoolTaskExecutor 它将 运行 TCPServer.

TCPServer 中我还有一个 class 注释为 @Repository。 如果我尝试调用 taskExecutor.execute(new TCPServer()) 这将不会由 Spring 管理,所以我的存储库对象将为空。

如何在 Main 中获取 TCPServer 的实例,以便将其提供给 taskExecutor?

TCP服务器:

@Component
@Scope("prototype")
public class TCPServer implements Runnable {

  @Autowired
  private StudentRepository studentRepository;
  //rest of code
}

学生资料库:

@Repository
public interface StudentRepository extends CrudRepository<Student, Long> {

}

我已经试过了:

TCPServer tcpServer = (TCPServer) applicationContext.getBean("tcpServer");

但这就是我得到的:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'tcpServer' available

编辑:

MySpringApplication: com.example.myspringapp;

TCPServer: com.example.myspringapp.server;

如果 class 被调用 TCPServer,bean 名称将是 TCPServer(显然 Spring 不会将第一个字符小写,如果 class 名称以一系列大写字符开头)。对于 bean 名称 tcpServer,class 名称必须是 TcpServer.

或者,您可以在组件注释中指定 bean 名称:

@Component("tcpServer")

要按类型获取 bean,您必须使用正确的类型。如果您的 class 实现了一个接口而您没有指定

@EnableAspectJAutoProxy(proxyTargetClass = true)

在您的主要配置 class 上,Spring 将使用默认的 JDK 代理来创建 bean,然后实现 class 的接口,而不是扩展 class 本身。所以在你的例子中 TCPServer 的 bean 类型是 Runnable.class 而不是 TCPServer.class.

因此要么使用 bean 名称来获取 bean,要么添加代理注释以使用 class 作为类型。