---
title: "spring中bean的范围(xml/annotation)"
author: "cdxs2"
date: "2013-09-11T23:27:09Z"
tags: []
categories: ["编程语言"]
slug: "spring-bean-xml-annotation"
draft: false
lastmod: "2013-09-12T23:57:26Z"
id: 1941078
url: "https://cdxs2.iteye.com/blog/1941078"
---

1.xml

配置文件bean.xml中，bean标签中的属性scope默认为singleton，表示每次创建的service和首次创建的是同一个对象，如果设置为prototype，表示每次创建的service是不同的对象。

```
<?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-2.5.xsd">

	<bean id="userDAOImpl" class="com.test.dao.impl.UserDAOImpl"></bean>
	<bean id="userService" class="com.test.service.UserService" scope="prototype">
		<property name="userDAO">
			<ref bean="userDAOImpl" />
		</property>
	</bean>
	
</beans>
```

 

2.annotation

UserDAOImpl.java

```
package com.test.dao.impl;

import org.springframework.stereotype.Component;

import com.test.dao.UserDAO;
import com.test.model.User;

@Component("userDAOImpl")
public class UserDAOImpl implements UserDAO {
	public void save(User user) {
		System.out.println("user saved!");
	}
}
```

 

UserService.java

```
package com.test.service;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.test.dao.UserDAO;
import com.test.model.User;

@Scope("prototype")
@Component("userService")
public class UserService {
	private UserDAO userDAO;

	public UserDAO getUserDAO() {
		return userDAO;
	}

	@Resource(name="userDAOImpl")
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void add(User user) {
		userDAO.save(user);
	}

}
```

 

公共junit测试类

UserServiceTest.java

```
package com.test.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.model.User;

public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		UserService service = (UserService) applicationContext.getBean("userService");
		UserService service2 = (UserService) applicationContext.getBean("userService");
		//scope默认是singleton(单例的意思)，这里打印值为true
		//scope设置为prototype(原型的意思)，每次创建新的对象，这里打印值为false
		System.out.println(service == service2);
		User u = new User();
		u.setUsername("zhangsan");
		u.setPassword("123");
		service.add(u);
	}

}
```