bean.xml:
注意, 千万不要后面加上 scope="prototype"
UserService.java:
package com.bjsxt.service;import com.bjsxt.dao.UserDAO;import com.bjsxt.model.User;public class UserService { private UserDAO userDAO; public void init() { System.out.println("init"); } public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public UserService(UserDAO userDAO) { super(); this.userDAO = userDAO; } public void destroy() { System.out.println("destroy"); }}
UserServiceTest.java:
package com.bjsxt.service;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.bjsxt.model.User;//Dependency Injection//Inverse of Controlpublic class UserServiceTest { @Test public void testAdd() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); UserService service = (UserService)ctx.getBean("userService"); UserService service2 = (UserService)ctx.getBean("userService"); ctx.destroy(); }}
结果init, init
去掉scope="prototype", 结果就是init, destroy