我有一个 RunBackgroundServices 类,它在启动时运行一些后台服务。我需要一个新的对象 BackgroundServices 在里面。所以我使用 WebApplicationContext 来获取 bean。但它不起作用。
运行后台服务.java
@WebListener
public class RunBackgroundServices implements ServletContextListener {
private ExecutorService executor;
public void contextInitialized(ServletContextEvent event) {
final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
BackgroundServices backgroundServices = springContext.getBean(BackgroundServices.class);
executor = Executors.newSingleThreadExecutor();
executor.submit(backgroundServices); // Task should implement Runnable.
}
public void contextDestroyed(ServletContextEvent event) {
executor.shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
后台服务.java
@Service
public class BackgroundServices extends Thread {
@Autowired
ServerListener serverListener;
@Autowired
ClientListener clientListener;
private static final Logger logger = LoggerFactory
.getLogger(BackgroundServices.class);
public void run() {
logger.debug("BackgroundServices :: run"); …Run Code Online (Sandbox Code Playgroud)