【发布时间】:2017-10-24 11:29:05
【问题描述】:
我有一个 Spring Web 应用程序,其中有多个 Service 和 DAO 类。在正常的 crud 操作中,一切正常。但是我在线程中注入依赖时遇到了问题。
在我的应用程序中,我需要创建一个线程并按需执行它。为此,我在控制器类中创建了如下线程。
TestThread testThread = new TestThread();
Thread thread = new Thread(testThread);
thread.start();
在我的线程中,我试图获得如下所示的依赖项。
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
TestService testService = (TestService) context.getBean("myService");
我的服务类如下所示。
@Service("myService")
public class TestServiceImpl implements TestService {
some methods...
}
但每次我都遇到异常。
Exception in thread "Thread-21" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myService' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
【问题讨论】:
-
不要自己创建线程,可以使用@Async 代替。
-
我为什么要使用@Async 而不是创建线程。
-
这是因为 Spring 检测了它操作的所有内容。如果你自己实例化一个新线程,那不关 Spring 的事。你不能创建一个名为 myTestThread 的 Spring bean,它会被 Spring 正确和完全初始化,包括你的线程中的服务?
-
如果我需要创建多个Callable线程并在前一个线程成功返回后一个一个执行?我能做到吗?
-
...显然“myService”(真的)不在您的“当前 Web 应用程序上下文”中(可能在另一个(例如根)上下文中!??;)
标签: java spring multithreading