【问题标题】:How to autowire classes in unmanaged instances?如何在非托管实例中自动装配类?
【发布时间】:2014-01-28 12:54:16
【问题描述】:

我有一个在服务器启动时创建的类。它用作客户端应用程序的入口方法。我无法改变这种行为。

虽然我想在这个非托管类中使用 Spring @Autowired。我读到aspectj编织可能是要走的路。好像已经按照日志执行了:

2014-01-28 13:11:10,156 INFO org.springframework.context.weaving.DefaultContextLoadTimeWeaver: Using a reflective load-time weaver for class loader: org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader

但我注入的Dao 服务仍然是null。可能缺少什么?

@WebListener
public class MyContextListener implements ServletContextListener {
        @Override
            public void contextInitialized(ServletContextEvent sce) {
            new TestService().run(); //throws NPE
        }
}

@Configurable
class TestService extends AbstractLegacyService {       
    @Autowired
    private Dao dao;

    @Override
    public void run() {
        //dao is always null
        dao.find();
    }
}


@Component
class Doa dao;

启用编织(tomcat):

@Configuration
@EnableLoadTimeWeaving
@EnableSpringConfigured
public class AppConfig {
}

【问题讨论】:

  • 你能显示web.xml吗?尤其是注册上下文监听器的部分。
  • 注解注册的。 web.xml 没有定义任何监听器。
  • 我认为您仍然需要有一个 bean 定义,以便 TestService 用作模板。也不要忘记您的组件扫描。
  • @SotiriosDelimanolis OP 使用加载时编织器。如果是@Configurable,则加载时编织器会注入使用new 运算符创建的对象。它适用于生命周期在 Spring 容器之外管理的 bean。
  • @RenéLink 并根据documentationSpring will configure new instances of the annotated type ( Account in this case) using a bean definition (typically prototype-scoped) with the same name as the fully-qualified type name ( com.xyz.myapp.domain.Account).

标签: java spring dependency-injection aspectj load-time-weaving


【解决方案1】:

您必须确保在调用MyContextListener 之前调用ContextLoaderListener

ContextLoaderListener初始化spring容器,加载时编织器只有在spring容器初始化的情况下才能注入TestService的依赖。

【讨论】:

  • 我刚刚发现,如果我将实现更改为 @WebListener class MyContextListener extends ContextLoaderListener 并相应地覆盖与我的帖子类似的 init 和 destroy 方法,整个 spring 注入就会按预期工作。
  • 是的,这也是一个解决方案。取决于MyContextListener 所做的事情以及如果您想在另一个上下文中使用它(可能是非弹簧上下文),是否从ContextLoaderListener 扩展是有意义的。
猜你喜欢
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2010-11-03
  • 2020-07-09
相关资源
最近更新 更多