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

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

获取的 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