我有我的TCPServer
类实现Runnable
并注释了@Component
。 而且我有一个ThreadPoolTaskExecutor
它将运行TCPServer
。春天 - 在主要使用@Component注释类的正确方法
在TCPServer
我也有一个类,它是注释与@Repository
。 如果我尝试调用taskExecutor.execute(new TCPServer())
,这将不会由Spring管理,因此我的存储库对象将为空。
我怎样才能得到TCPServer
的实例在Main
,所以我可以把它给taskExecutor?
TCPSERVER:
@Component
@Scope("prototype")
public class TCPServer implements Runnable {
@Autowired
private StudentRepository studentRepository;
//rest of code
}
StudentRepository:
@Repository
public interface StudentRepository extends CrudRepository<Student, Long> {
}
我已经尝试过这样的:
TCPServer tcpServer = (TCPServer) applicationContext.getBean("tcpServer");
但是,这是我得到:
异常线程 “main” org.springframework.beans.factory.NoSuchBeanDefinitionException:无豆命名为 'TCPSERVER' 可用
编辑:
MySpringApplication
:com.example.myspringapp;
TCPServer
:com.example.myspringapp.server;
也许这只是一个命名问题http://stackoverflow.com/questions/10967279/is-spring-getbean-case-sentitive-or-not你尝试命名你的班'TcpServer',并用最后一行恢复它你指出? – RubioRic
使用'applicationContext.getBean(“tcpServer”)'获取bean是正确的。可能bean'TCPServer'没有被创建。我怀疑它不在主类包的子包中。你可以添加主应用类和TCPServer类的包吗? –
也尝试通过'TCPServer tcpServer =(TCPServer)applicationContext.getBean(TCPServer.class)'类型来投注Bean;' –