2017-04-30 30 views
1

我有我的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' 可用

编辑:

MySpringApplicationcom.example.myspringapp;

TCPServercom.example.myspringapp.server;

+0

也许这只是一个命名问题http://stackoverflow.com/questions/10967279/is-spring-getbean-case-sentitive-or-not你尝试命名你的班'TcpServer',并用最后一行恢复它你指出? – RubioRic

+0

使用'applicationContext.getBean(“tcpServer”)'获取bean是正确的。可能bean'TCPServer'没有被创建。我怀疑它不在主类包的子包中。你可以添加主应用类和TCPServer类的包吗? –

+0

也尝试通过'TCPServer tcpServer =(TCPServer)applicationContext.getBean(TCPServer.class)'类型来投注Bean;' –

回答

2

如果这个类名为TCPServer,那么bean的名字将是TCPServer(显然,如果类名以大写字母序列开头,Spring不会小写第一个字符)。对于豆名tcpServer,类名称必须是TcpServer

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

@Component("tcpServer") 

按类型获取豆,你必须使用正确的类型。如果您的类实现一个接口,你没有在您的主要配置类指定

@EnableAspectJAutoProxy(proxyTargetClass = true) 

,Spring将使用默认的JDK代理创建豆,其实施则类的接口,并且不延长课本身。所以在你的情况下,TCPServer的bean类型是Runnable.class而不是TCPServer.class

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

+0

'TCPServer tcpServer = applicationContext.getBean(TCPServer.class); '这给出了相同的结果 –

+0

是的,因为你的类实现了一个接口。那么如果你没有指定正确的代理模式,那么你的bean的类型就是接口。将编辑到我的答案。 – dunni

+0

工作就像一个魅力。感谢您的帮助和解释。直到现在还不知道。 –