Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML-less configuration for spring

Tags:

java

spring

I have the following configuration bean for a non web app

@Configuration
public class MyBeans {

    @Bean
    @Scope(value="prototype")
    MyObject myObject() {
        return new MyObjectImpl();
    }
}

On the other side I have my class

public class MyCommand implements Command {

  @Autowired
  private MyObject myObject;

  [...]

}

How can I make myCommand be autowired with the configuration in MyBeans without using XML so I can inject mocks in my other test classes?

Thanks a lot in advance.

like image 393
Rafa de Castro Avatar asked Dec 15 '25 14:12

Rafa de Castro


1 Answers

With XML-based configuration you'd use the ContextConfiguration annotation. However, the ContextConfiguration annotation doesn't appear to work with Java Config. That means that you have to fall back on configuring your application context in the test initialization.

Assuming JUnit4:

@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest{

    private ApplicationContext applicationContext;

    @Before
    public void init(){
        this.applicationContext = 
            new AnnotationConfigApplicationContext(MyBeans.class);

            //not necessary if MyBeans defines a bean for MyCommand
            //necessary if you need MyCommand - must be annotated @Component
            this.applicationContext.scan("package.where.mycommand.is.located");
            this.applicationContext.refresh(); 

        //get any beans you need for your tests here
        //and set them to private fields
    }

    @Test
    public void fooTest(){
        assertTrue(true);
    }

}
like image 136
Ben Burns Avatar answered Dec 17 '25 08:12

Ben Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!