生命周期回调
1. 使用接口的方式实现:
1.初始化回调 实现InitializingBean 重写afterPropertiesSet
2.销毁回调 实现DisposableBean 重写destroy
2.自定义init()和destroy()
// 实例化
public void initByConfig() throws Exception {
System.out.println("实例化Person2");
}
// 销毁
public void destroyByConfig() throws Exception {
System.out.println("销毁Person2");
} 注意:先调用接口的回调方法,然后才会掉自定义的回调方法。 |
3. 基于配置的方式实现
直接在实体类的方法上添加注解就可以了。
// 生命周期回调 初始化回调
@PostConstruct
public void init(){
System.out.println("初始化");
}
// 生命周期回调 销毁回调
@PreDestroy
public void destory(){
System.out.println("销毁");
}
一般不会将一个实体类注册为一个bean,比如在实体类上加@Component;一般不会给接口添加bean注解,虽然不报错但是没意义,因为ioc压根就不识别接口,只识别类。
@Test
public void test06() {
//可以通过接口拿到它对应的实现类
UserService bean = ioc.getBean(UserService.class);
System.out.println(bean.getClass());
RoleServiceImpl roleService=new RoleServiceImpl();
// instanceof 用户判断前面的对象是否是后面的类,或者子类,或者接口
if(roleService instanceof RoleService)
{
System.out.println("OK");
//RETURN
}
}



