Bean的作用域

单例模式 singleton(xml默认作用域)

配置

<!--singleton:单例模式,在Spring容器中拿到的都是同一个对象-->
    <bean id="user" class="com.Google.pojo.user" p:age="19" p:name="Spring" scope="singleton"/>

测试

@Test
    public  void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        user user = context.getBean("user", user.class);
        user user1 = context.getBean("user", user.class);
        System.out.println(user==user1);
    }

结果

true

原型模式 prototype

配置

<!--prototype:原型模式,在Spring容器中拿到的对象都是不同的-->
    <bean id="user1" class="com.Google.pojo.user" c:age="20" c:name="Spring1" scope="prototype"/>

测试

 @Test
    public  void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        user user = context.getBean("user1", user.class);
        user user1 = context.getBean("user1", user.class);
        System.out.println(user==user1);
    }

结果

false

当然Bean的作用域不止这么点,还有request,Session,Application 等。剩下的都是有Web方面的作用域,我们在javaWeb中都学习过了,这里就不再赘述。

posted @ 2022-02-07 23:01  小罗要有出息  阅读(21)  评论(0编辑  收藏  举报