使用@Autowired和ApplicationContext注入bean或获取bean之间的区别

时间:2018-07-30 10:33:29

标签: java spring

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ShoppingCart.class})
public class ShoppingCartTest {
    private ApplicationContext context = new AnnotationConfigApplicationContext(ShopConfiguration.class);
    @Autowired
    private ShoppingCart shoppingCart;

    @Test
    public void testShoppingCartCreation() {
        Product battery = (Product) context.getBean("battery");
        Product cdrw = (Product) context.getBean("cdrw");
        Product dvdrw = (Product) context.getBean("dvder");
        ShoppingCart shoppingCart1 = context.getBean(ShoppingCart.class);
        shoppingCart1.addItem(battery);
        shoppingCart1.addItem(cdrw);
        Assert.assertEquals(false, shoppingCart.getItems().isEmpty());
    }

}

有人可以解释一下为什么这段代码将为购物车创建两个具有默认范围的对象,以及它们将出现在哪个容器中以及它们之间的区别。

0 个答案:

没有答案