小编Abh*_*odi的帖子

在 Spring 启动时注入 bean

我有一个 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)

spring dependency-injection

0
推荐指数
1
解决办法
956
查看次数

标签 统计

dependency-injection ×1

spring ×1