XML-free configuration for spring

I have the following bean configuration for a non-web application

@Configuration
public class MyBeans {

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

On the other hand, I have a class

public class MyCommand implements Command {

  @Autowired
  private MyObject myObject;

  [...]

}

How can I do myCommand automatically with customization in MyBeans without using XML so that I can inject mocks into other test classes?

Thank you very much in advance.

+3
source share
1 answer

Using the XML configuration, you must use the ContextConfiguration annotation. However, the ContextConfiguration annotation does not work with Java Config. This means that you will have to abandon the context setting of your application in the initialization of the test.

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);
    }

}
+1
source

All Articles