<?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.xsd">
<!-- 注册service
SomeServiceImpl myService=new SomeServiceImpl();
-->
<!-- init-method 将要创建完成执行(完成后)-->
<!-- destroy-method 将要销毁之前执行-->
<bean id="myService" class="com.gqc.ba06.SomeServiceImpl"
init-method="setUp" destroy-method="tearDown"
/>
</beans>
package com.gqc.ba06;
public class SomeServiceImpl implements ISomeService {
private int a;
public SomeServiceImpl(int a) {
super();
this.a = a;
}
public SomeServiceImpl() {
System.out.println("执行无参构造器");
}
@Override
public void doSome() {
System.out.println("ִ执行doSome()");
}
//自定义的方法 可以在将要创建完成之前执行
public void setUp(){
System.out.println("生命启始");
}
//自定义的方法 可以在销毁之前执行
public void tearDown(){
System.out.println("销毁之前 ");
}
}
package com.gqc.ba06;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class MyTest {
@Test
public void test01() {
//创建容器对象 加载Spring 配置文件
String resource = "com/gqc/ba06/appliactionContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService)ac.getBean("myService");
service.doSome();
//对于销毁方法的执行 有两个条件
//1、当前的bean 是singleton的
//2、需要关闭容器
((ClassPathXmlApplicationContext)ac).close();
}
}
package com.gqc.ba06;
public interface ISomeService {
void doSome();
}