微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何覆盖Spring @Autowire注释并将字段设置为null?

我是Spring新手,正在开发一个基于Spring的大型项目,它在Spring bean之间有广泛的耦合.我正在尝试编写一些集成测试来执行整个应用程序功能的子集.为此,我想覆盖一些自动装配.
例如,假设我有一个班级

public class MyDataServiceImpl implements MyDataService {
    @Qualifier("notNeededForMyDataServiceTest")
    @Autowired
    private NotNeededForMyDataServiceTest notNeededForMyDataServiceTest;
    //...
}
@H_404_8@

一个上下文文件

404_8@

在我的测试中,我不需要使用notNeededForMyDataServiceTest字段.有没有什么方法可以覆盖@Autowired注释并将notNeededForMyDataServiceTest设置为null,可能在XML文件中?我不想修改任何java类,但我确实想避免notNeededForMyDataServiceTest的(有问题的)配置.

我试过做:

404_8@

这不起作用. IntelliJ告诉我“无法解析属性’notNeededForMyDataServiceTest’”,显然是因为该字段没有getter和setter.

我正在使用Spring Framework 3.1.3.

最佳答案
以下配置应该可行,我冒昧地在Java配置中混合

@Configuration
//This will load your beans from whichever xml file you are using
@ImportResource("classpath:/path/beans.xml")
public class TestConfigLoader{
    // This will declare the unused bean and inject MyDataServiceImpl with null.
    public @Bean(name="notNeededForMyDataServiceTest") NotNeededForMyDataServiceTest getNotNeededForMyDataServicetest(){
        return null;
    }
... any other configuration beans if required.
}
@H_404_8@

并注释您的测试类,如下所示:

// In your test class applicationContext will be loaded from TestConfigLoader
@ContextConfiguration(classes = {TestConfigLoader.class})
public class MyTest {
    // class body...
}
@H_404_8@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐