I have my TCPServer
class implementing Runnable
and annotated with @Component
.
And I have a ThreadPoolTaskExecutor
which will run the TCPServer
.
In TCPServer
I also have a class which is annotated with @Repository
.
If I try to call taskExecutor.execute(new TCPServer())
this will not be managed by Spring so my repository object will be null.
How can I get an instance of TCPServer
in Main
so I can give it to 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> {
}
I already tried like this:
TCPServer tcpServer = (TCPServer) applicationContext.getBean("tcpServer");
But this is what I got:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'tcpServer' available
Edit:
MySpringApplication
: com.example.myspringapp;
TCPServer
: com.example.myspringapp.server;
If the class is called TCPServer
, the bean name will be TCPServer
(apparently Spring doesn't lowercase the first character, if the class name starts with a sequence of uppercase characters). For the bean name tcpServer
, the class name has to be TcpServer
.
Alternatively, you can specify the bean name in the Component annotation:
@Component("tcpServer")
For getting the bean by type, you have to use the correct type. If your class implements an interface and you didn't specify
@EnableAspectJAutoProxy(proxyTargetClass = true)
on your main configuration class, Spring will use default JDK proxies to create the beans, which implement then the interfaces of the class and don't extend the class itself. So the bean type of TCPServer
in your case is Runnable.class
and not TCPServer.class
.
So either use bean names to get the bean or add the proxy annotation to use the class as type.