免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
1、豆のライフサイクル
作成ビーン-初期化-破壊
構造(オブジェクトの作成):
シングル・インスタンス:活性化されると、コンテナ内のオブジェクトを作成するために、
マルチ・インスタンス:たびに取得オブジェクトを作成するために、
初期化:
オブジェクトが作成され、良好な割り当て、初期化メソッドが呼び出される
破壊。
単一インスタンス、容器が閉じているとき、
マルチインスタンス:コンテナはBeanを管理していない、容器呼び出しメソッドを破壊します
2、カスタム初期化メソッドと破壊の方法
2.1、@Bean指定初期化メソッド(にinitMethod)及び破壊の方法によって(destroyMethodを)
- MainConfigLifeCycle类
@Configuration
public class MainConfigLifeCycle {
@Bean(initMethod = "init", destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
- 車のカテゴリ
public class Car {
public Car() {
System.out.println("new car");
}
public void init() {
System.out.println("car init");
}
public void destroy() {
System.out.println("car destroy");
}
}
- IOCTest_LifeCycleクラス
@Test
public void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
System.out.println("容器初始化");
context.close();
}
2.2は、Bean実装InitializingBeanインタフェース(定義されたインターフェースの初期化)可能にすることによって、DisposableBeanインタフェース(インタフェースを破壊し)
- Catクラス
@Component
public class Cat implements InitializingBean,DisposableBean {
public Cat() {
System.out.println("new cat");
}
public void destroy() throws Exception {
System.out.println("cat destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("cat afterPropertiesSet");
}
}
- MainConfigLifeCycle类
@ComponentScan("com.dav.bean")
@Configuration
public class MainConfigLifeCycle {
}
- IOCTest_LifeCycleクラス
@Test
public void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
System.out.println("容器初始化");
context.close();
}
JSR250注釈のJAVAを使用して2.3、
@PostConstruct:Beanの作成が完了し、プロパティの割り当てが完了すると、初期化メソッドを実行するために、
@PreDestroy:私たちは豆の容器の破壊前にクリーンアップしていきましょう。
- Dogクラス
@Component
public class Dog {
public Dog() {
System.out.println("new dog");
}
@PostConstruct
public void init() {
System.out.println("dog @PostConstruct");
}
@PreDestroy
public void destroy() {
System.out.println("dog @PreDestroy");
}
}
- MainConfigLifeCycle类
@ComponentScan("com.dav.bean")
@Configuration
public class MainConfigLifeCycle {
}
- IOCTest_LifeCycleクラス
@Test
public void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
System.out.println("容器初始化");
context.close();
}