Junite 中测试@Autowired无法生效的原因

    xiaoxiao2022-07-07  207

    package IOCReview;

    import static org.junit.Assert.*;

    import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    /**   * @ClassName: IOC入门Test   * @Description: TODO(这里用一句话描述这个类的作用)   * @author Administrator   * @date 2019年5月15日   *     */ @RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!  @ContextConfiguration({"classpath:applicationContext.xml"})  //用于加载bean public class IOCTest {          @Autowired     public Car car;          @Test     public void testName() throws Exception {         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");         UserDao dao=(UserDao) context.getBean("UserDao");         dao.save();     }          @Test     public void testCar() throws Exception {         System.out.println(car.getName()+"   "+car.getPrice());     } }

     

     

    以上是我通过ClassPathXmlApplicationContext 以及  @Autowired 测试IOC的例子

    后面测试@Autowired  遇到困难,无法自动注入Bean

    经过检查,发现首先要映入spring-test的框架,其次要加载bean文件,这是我在网上查到的

    不过我测试的时候还是不行,后面检查发现是spring-test的版本太高了,最后引入4.1.3才OK

    @RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!  @ContextConfiguration({"classpath:applicationContext.xml"})  //用于加载bean

    最新回复(0)