在测试的时候 我们还是需要获取ioc容器 然后在容器里获取对象服务类对象 而不能直接从容器里获取对象
    我们需要整合junit 就能在测试类里直接获取ioc里的任何对象

    首先要导入整合包和junit包

    然后在测试类上面写@RunWith(SpringJUnit4ClassRunner.class)
    在测试类上面写@ContextConfiguration(classes ={SpringConfig.class} ) 找到容器

    1. @RunWith(SpringJUnit4ClassRunner.class)//替换JUnit4运行器(固定写法)
    2. //@ContextConfiguration(value = {"classpath:a.xml","classpath:b.xml"})//加载xml构建ioc容器
    3. @ContextConfiguration(classes ={SpringConfig.class} )//通过配置类构建IOC容器
    4. public class SpringTest {
    5. @Autowired
    6. private AccountService accountService;
    7. /**
    8. * 存在的问题:
    9. * 关注点分离:
    10. * 当前在进行测试时,我们可能仅仅需要从测试某个服务的执行是否ok
    11. * 但是为了执行对应的代码,还需要引入很多我们不需要关注的代码,比如:
    12. * ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    13. * AccountService accountService = ctx.getBean(AccountService.class);
    14. * 如果我们想测试什么bean,就直接注入什么bean,那该多好!
    15. */
    16. @Test
    17. public void test01(){
    18. // ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    19. // AccountService accountService = ctx.getBean(AccountService.class);
    20. //不用再新建上下文 通过名字获取对象 而是直接注入此类型的对象
    21. Account ac = accountService.findById(1);
    22. System.out.println(ac);
    23. }
    24. }