package com.zt.spring;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class User implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("=======afterPropertiesSet========");
}
@Override
public void destroy() throws Exception {
System.out.println("=======destroy========");
}
}
1.2.1.2在conffig文件中装配这个bean
package com.zt.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBeanConfig {
@Bean
public User createUser() {
return new User();
}
}
1.2.1.3 获取上下文
package com.zt.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
// 获取上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBeanConfig.class);
System.out.println(context.getBean(User.class));
context.close();
}
}
1.2.2 调用自定义初始化和销毁的方法
1.2.2.1 创建一个bean
自定义init,destroy方法
package com.zt.spring;
public class Dog {
// 初始化方法
public void init() throws Exception {
System.out.println("=======init========");
}
// 销毁的方法
public void destroy() throws Exception {
System.out.println("=======destroy========");
}
}
1.2.2.2在conffig文件中装配这个bean
package com.zt.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBeanConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Dog createDog() {
return new Dog();
}
}
1.2.2.3 获取上下文
package com.zt.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
// 获取上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBeanConfig.class);
System.out.println(context.getBean(Dog.class));
context.close();
}
}