测试代码
@Test
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Cat cat = context.getBean("cat", Cat.class);
context.close();
}
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 通过注解的方式自动装配-->
<context:annotation-config/>
<bean id="dog" class="com.nanhua.pojo.Dog"/>
<bean id="cat" class="com.nanhua.pojo.Cat"/>
<bean id="people" class="com.nanhua.pojo.People"/>
</beans>
测试截图
方案一、通过init-method 和 destory-method方法
配置
<bean id="cat" class="com.nanhua.pojo.Cat" init-method="init" destroy-method="destroy"/>
代码
public class Cat{
public void shout() {
System.out.println("miao~");
}
public void init(){
System.out.println(this.getClass().getCanonicalName()+"创建了");
}
public void destroy(){
System.out.println(this.getClass().getCanonicalName()+"销毁了");
}
}
方案二、通过@PostConstruct和@PreDestroy注解
public class Cat{
public void shout() {
System.out.println("miao~");
}
@PostConstruct
public void init(){
System.out.println(this.getClass().getCanonicalName()+"创建了");
}
@PreDestroy
public void destroy(){
System.out.println(this.getClass().getCanonicalName()+"销毁了");
}
}
方案三、实现bean实现InitializingBean和DisposableBean接口
public class Cat implements InitializingBean, DisposableBean {
public void shout() {
System.out.println("miao~");
}
public void afterPropertiesSet() throws Exception {
System.out.println(this.getClass().getCanonicalName() + "创建了");
}
public void destroy() throws Exception {
System.out.println(this.getClass().getCanonicalName() + "销毁了");
}
}