How to autowire field in static @BeforeClass?

后端 未结 5 1304
天命终不由人
天命终不由人 2021-01-31 07:56
@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
    @Autowired
    private EntityRepository dao;

    @BeforeClass
    public static void init() {
        da         


        
5条回答
  •  自闭症患者
    2021-01-31 08:34

    To answer this question we should recap Spring 2.x versions.

    If you want to "autowire" a bean in your @BeforeTest class you can use the ApplicationContext interface. Let's see an example:

    @BeforeClass
        public static void init() {
            ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
            EntityRepository dao2 = (EntityRepository) context.getBean("dao");
            List all = dao2.getAll();
            Assert.assertNotNull(all);
        }
    

    What's happening: using the ClassPathXmlApplicationContext we are instantiating all beans contained in the application-context.xml file.

    With context.getBean() we read the bean specified (it must match the name of the bean!); and then you can use it for your initialization.

    You should give to the bean another name (that's the dao2!) otherwise Spring normal "autowired" cannot work on the predefined bean.

    As a side note, if your test extends AbstractTransactionalJUnit4SpringContextTests you can do some initialization using executeSqlScript(sqlResourcePath, continueOnError); method, so you don't depend on a class/method that you also have to test separately.

提交回复
热议问题