【问题标题】:Spring-instrument and auto injection in new object新对象中的弹簧仪器和自动注入
【发布时间】:2012-08-01 08:11:27
【问题描述】:

我有 spring 3.1 应用程序。我有 spring-instrument java 代理,我有可配置的类:

@Configurable
public class WeavingClass {

    @Resource
    @Getter
    private ApplicationContext ac;

    public WeavingClass()
    {

    }

}

并进行单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={WebBackendContextConfig.class})
@Slf4j
public class TestWeavingInjection extends TestCase {

    @Test
    public void isInjectedTest()
    {
        WeavingClass wc = new WeavingClass();
        assertNotNull(wc.getAc());
    }
}

还有:

@Configuration
@PropertySource(value={"classpath:META-INF/conf/liteicms-backend.properties"})
@ComponentScan(value={"ru.icb.liteicms.backend.service", "ru.icb.liteicms.domain", "ru.icb.liteicms.backend.domain.contentpage.wrappers"})
@EnableSpringConfigured
@EnableLoadTimeWeaving
@EnableAspectJAutoProxy
public class WebBackendContextConfig {

}

我使用 -javaagent:org.springframework.instrument-3.1.1.RELEASE.jar 运行我的测试 我的测试没有错误。

但是如果我添加这个:

private HashMap<Class<?>, Class<?>> builderMap = new HashMap<Class<?>, Class<?>>()
{
    private static final long serialVersionUID = 1L;
    {
    put(String.class, WeavingClass.class);
    }
};

我的测试失败了。

【问题讨论】:

  • 您是否将命令行参数传递给运行 junit 测试的 jvm 以启动检测代理,例如 -javaagent:org.springframework.instrument-3.1.1.RELEASE.jar
  • 当然可以。如果我使用 hashmap init 删除部分,测试将起作用。
  • 你把HashMap 的东西放在哪里了,你确定所有的嵌套块都放在那里吗?
  • 我的代码中的任何地方。例如在测试中。

标签: java spring hashmap code-injection


【解决方案1】:

注入new-created 对象(而不是托管 bean)只能通过编译或加载时编织,而不是 Spring 默认使用的运行时代理。

您需要配置一个 AspectJ 编织器 &lt;context:load-time-weaver&gt;,或使用命令行选项启动 JVM 以启用 InstrumentationSavingAgent

Details from the Spring documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2019-03-19
    • 2013-01-23
    相关资源
    最近更新 更多