11、bean对象的初始化和销毁方法
在创建对象的时候,我们可以根据需要调用初始化和销毁的方法
Address.java
package com.mashibing.bean;
public class Address {
private String province;
private String city;
private String town;
public Address() {
System.out.println("address");
}
public Address(String province, String city, String town) {
this.province = province;
this.city = city;
this.town = town;
}
public void init(){
System.out.println("对象被初始化");
}
public void destory(){
System.out.println("对象被销毁");
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
", town='" + town + '\'' +
'}';
}
}
ioc.xml
<!--bean生命周期表示bean的创建到销毁
如果bean是单例,容器在启动的时候会创建好,关闭的时候会销毁创建的bean
如果bean是多例,获取的时候创建对象,销毁的时候不会有任何的调用
-->
<bean id="address" class="com.mashibing.bean.Address" init-method="init" destroy-method="destory" scope="prototype"></bean>
SpringDemoTest.java
import com.mashibing.bean.Address;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemoTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("ioc1.xml");
Address address = context.getBean("address", Address.class);
System.out.println(address);
//applicationContext没有close方法,需要使用具体的子类
((ClassPathXmlApplicationContext)context).close();
}
}
12、配置bean对象初始化方法的前后处理方法
spring中包含一个BeanPostProcessor的接口,可以在bean的初始化方法的前后调用该方法,如果配置了初始化方法的前置和后置处理器,无论是否包含初始化方法,都会进行调用
ioc.xml
<bean id="myBeanPostProcessor" class="com.mashibing.bean.MyBeanPostProcessor"></bean>
标签:town,city,province,String,spring,bean,赋值,public,属性 From: https://www.cnblogs.com/shanqiang1/p/17723962.html