明天你会感谢今天奋力拼搏的你。
ヾ(o◕∀◕)ノヾ
package com.cyx.initdemo;
import org.springframework.context.annotation.*;
@Configuration
public class MyInitConfig {
@Bean(initMethod = "initMethod",destroyMethod = "destroyMethod")
public MyEntity myEntity(){
return new MyEntity ();
}
}
class MyEntity {
public MyEntity(){
System.out.println("执行了MyEntity无参构造函数》》》》》》");
}
private void initMethod(){
System.out.println("执行了init方法》》》》》》》》》》》》");
}
private void destroyMethod(){
System.out.println("执行了 destroy方法》》》》》》》》》》》》》");
}
}
测试代码如下:
package com.cyx.initdemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestInit {
public static void main (String[] args){
//以注解的方式执行
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyInitConfig.class);
//获取对象
MyEntity myEntity = context.getBean("myEntity", MyEntity.class);
System.out.println(myEntity.toString());
//再次调用
MyEntity myEntity2 = context.getBean("myEntity", MyEntity.class);
System.out.println(myEntity2.toString());
//销毁
context.close();
}
}
执行结果:
package com.cyx.initdemo;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.*;
@Configuration
public class MyInitConfig {
@Bean
public MyEntity myEntity(){
return new MyEntity ();
}
}
class MyEntity implements InitializingBean, DisposableBean {
public MyEntity(){
System.out.println("执行了MyEntity无参构造函数》》》》》》");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行了init方法》》》》》》》》》》》》");
}
@Override
public void destroy() throws Exception {
System.out.println("执行了 destroy方法》》》》》》》》》》》》》");
}
}
同样的测试类,执行结果如下:
package com.cyx.initdemo;
import org.springframework.context.annotation.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Configuration
public class MyInitConfig {
@Bean
public MyEntity myEntity(){
return new MyEntity ();
}
}
class MyEntity{
public MyEntity(){
System.out.println("执行了MyEntity无参构造函数》》》》》》");
}
@PostConstruct
public void afterPropertiesSet() throws Exception {
System.out.println("执行了init方法》》》》》》》》》》》》");
}
@PreDestroy
public void destroy() throws Exception {
System.out.println("执行了 destroy方法》》》》》》》》》》》》》");
}
}
测试结果相同:
全部评论