menu Error0 Blog
Spring Bean 作用域
6086 浏览 | 2019-08-02 | 分类:Spring | 标签:
  1. singleton 在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,默认值
  2. prototype 每次调用getBean()时,相当于执行newXxxBean()
  3. request 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境
  4. session 同一个HTTP Session共享一个Bean,不同Session使用不同的Bean,仅适用于WebApplicationContext环境

singleton示例

main代码

ApplicationContext context=new ClassPathXmlApplicationContext("springbean.xml");
        hello a=(hello) context.getBean("hello");
        hello b=(hello) context.getBean("hello");
        a.setName("你好 Spring");
        System.out.println(a.getName());
        System.out.println(b.getName());

springBean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      <bean id="hello" class="springbean.hello" scope="singleton">
      
      </bean>
</beans>

输出结果

prototype示例

main代码

ApplicationContext context=new ClassPathXmlApplicationContext("springbean.xml");
        hello a=(hello) context.getBean("hello");
        hello b=(hello) context.getBean("hello");
        a.setName("你好 Spring");
        System.out.println(a.getName());
        System.out.println(b.getName());

springBean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      <bean id="hello" class="springbean.hello" scope="prototype">
      
      </bean>
</beans>

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

发表评论

email
web

全部评论 (暂无评论)

info 还没有任何评论,你来说两句呐!

Emoji

Warning: file_get_contents(/assets/json/owo.json): failed to open stream: No such file or directory in /www/wwwroot/build/usr/themes/Cuckoo/includes/owo.php on line 46

Warning: array_keys() expects parameter 1 to be array, null given in /www/wwwroot/build/usr/themes/Cuckoo/includes/owo.php on line 48

Warning: file_get_contents(/assets/json/owo.json): failed to open stream: No such file or directory in /www/wwwroot/build/usr/themes/Cuckoo/includes/owo.php on line 87

Warning: array_keys() expects parameter 1 to be array, null given in /www/wwwroot/build/usr/themes/Cuckoo/includes/owo.php on line 89