Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a Spring @Autowire annotation and set a field to null?

Tags:

spring

I am a Spring neophyte who is working on a large Spring-based project that has extensive coupling between Spring beans. I am trying to write some integration tests that exercise subsets of the total application functionality. To do so, I'd like to override some of the autowiring. For example, suppose I have a class

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

and a context file with:

<bean id="myDataService"
      class="MyDataServiceImpl">
</bean>

In my test, I have no need to use the notNeededForMyDataServiceTest field. Is there some way I can override the @Autowired annotation and set notNeededForMyDataServiceTest to null, perhaps in the XML file? I don't want to modify any of the Java classes, but I do want to avoid the (problematic) configuration of notNeededForMyDataServiceTest.

I tried doing:

<bean id="myDataService"
      class="MyDataServiceImpl">
    <property name="notNeededForMyDataServiceTest"><null/></property>
</bean>

That doesn't work. IntelliJ informs me "Cannot resolve property 'notNeededForMyDataServiceTest'", apparently because there are no getters and setters for that field.

I'm using Spring Framework 3.1.3.

like image 213
kc2001 Avatar asked Jul 25 '13 18:07

kc2001


2 Answers

The following configuration should work, I took the liberty of mixing in Java configuration

@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.
}

And annotate your test class like so:

// In your test class applicationContext will be loaded from TestConfigLoader
@ContextConfiguration(classes = {TestConfigLoader.class})
public class MyTest {
    // class body...
}
like image 168
Abe Avatar answered Nov 08 '22 23:11

Abe


These could help:

  • Context configuration with annotated classes
  • Testing with @Configuration Classes and Profiles
  • Spring TestContext Framework

and profiles:

  • beans profile="..."
  • Introducing @Profile

You could create different beans definition in the XML configuration and then activate them using the -Dspring.profiles.active="profile1,profile2" env.

like image 25
David Riccitelli Avatar answered Nov 08 '22 23:11

David Riccitelli