Spring指定Bean的初始化方法和销毁方法
程序员文章站
2022-05-21 23:06:22
...
package cn.itcast.service;
public interface PersonService {
public void save();
}
package cn.itcast.service.impl;
import cn.itcast.service.PersonService;
public class PersonServiceBean implements PersonService {
public void init() {
System.out.println("初始化");
}
public PersonServiceBean() {
System.out.println("我被实例化了");
}
public void save() {
System.out.println("我是save()方法");
}
public void destory() {
System.out.println("关闭打开的资源");
}
}
package junit.test;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.service.PersonService;
public class SpringTest {
@Test public void instanceSpring(){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//当lazy-init="true"时控制台没有任何信息,需要打开下面的注释
//当lazy-init="false"时控制台打印 我被实例化了 初始化 关闭打开的资源
//PersonService personService = (PersonService)ctx.getBean("personService");
//personService.save();
ctx.close();
}
}
<?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"> <!-- lazy-init参数为true时只有第一次获取bean会才初始化bean --> <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" lazy-init="true" init-method="init" destroy-method="destory"> </bean> </beans>