初學spring init-method="init" destroy-method="destroy" scope="prototype"
阿新 • • 發佈:2019-02-01
beans.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-2.5.xsd" >
<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
</bean>
<bean id="userService" class="com.bjsxt.service.UserService" init-method="init" destroy-method="destroy" scope="prototype">
<!--
<property name="userDAO" ref="u" />
-->
<constructor-arg >
<ref bean="u"/>
</constructor-arg>
</bean>
</beans>
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 Control
public 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();
}
}
當加了scope=”prototype”,前面兩個方法就沒用了,測試的結果是,執行new ClassPathXmlApplicationContext(“beans.xml”)不會初始化,而在呼叫getBean方法時,有兩次呼叫,就兩次初始化呼叫了init方法,最後沒有呼叫銷燬,如果去掉scope=”prototype”,new ClassPathXmlApplicationContext(“beans.xml”)就會初始化,只有一次,最後結束會呼叫銷燬方法。所以前面兩個不要和第三個一起用