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 @   小罗要有出息  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示