2017-04-30 45 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

工作就像一個魅力。感謝您的幫助和解釋。直到現在還不知道。 –