scope 作用域(bean 的生存范围)

默认是 singleton ,单例模式,如下代码:

 1     @Test
 2     public void testAddUser() throws Exception {
 3         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//初始化ApplicationContext对象,加载配置文件
 4         
 5         UserService service = (UserService)ctx.getBean("userService");//从容器中取
 6         UserService service2 = (UserService)ctx.getBean("userService");//从容器中取
 7         
 8         System.out.println(service == service2);//true
 9         
10         User u = new User();
11         u.setUsername("zhangsan");
12         u.setPassword("zhangsan");
13         service.addUser(u);//容器中已经配置了UserDAOImpl了,并把DAOImpl注入到service之中,所以service直接就可以保存了
14     }

  获取的 service 和 service2 都是一个对象,结果为true。

  如果将 scope 设置为 prototype: 1 <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype"> ,则每次调用getBean都会获取新的实例,结果就为false了;

  singleton 最常用;prototype 视情况而定。

  后面的几个配置一般在SpringMVC框架中才会涉及到,这里不做探讨。

代码链接: http://pan.baidu.com/s/1nu6KK9F 密码: ishj

jar包链接: http://pan.baidu.com/s/1qYRTGEo 密码: fejx

原文地址:https://www.cnblogs.com/ShawnYang/p/6879591.html