简体   繁体   中英

XML-less configuration for 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM