Bean管理

Bean作用范围

  1. public class App
  2. {
  3. public static void main( String[] args )
  4. {
  5. ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  6. BookDaoImpl bookDao1 = ctx.getBean(BookDaoImpl.class);
  7. BookDaoImpl bookDao2 = ctx.getBean(BookDaoImpl.class);
  8. System.out.println(bookDao1);
  9. System.out.println(bookDao2);
  10. }
  11. }

打印出来俩个Bean是同一个对象(单例)

  1. com.chentianyu.service.impl.BookDaoImpl@75f9eccc
  2. com.chentianyu.service.impl.BookDaoImpl@75f9eccc

变成非单例对象(@Scope)

  1. package com.chentianyu.Dao.impl;
  2. import com.chentianyu.service.BookDao;
  3. import org.springframework.context.annotation.Scope;
  4. import org.springframework.stereotype.Repository;
  5. @Repository
  6. @Scope("prototype") //singleton:单例 ; prototype:非单例
  7. public class BookDaoImpl implements BookDao {
  8. }
  1. com.chentianyu.Dao.impl.BookDaoImpl@75f9eccc
  2. com.chentianyu.Dao.impl.BookDaoImpl@52aa2946

Bean生命周期

自定义的生命周期名称叫什么都可以

  1. @Repository
  2. @Scope("singleton") //singleton:单例 ; prototype:非单例
  3. public class BookDaoImpl implements BookDao {
  4. public void save(){
  5. System.out.println("book dao save...");
  6. }
  7. @PostConstruct //构造方法后
  8. public void init(){
  9. System.out.println("book dao init...");
  10. }
  11. @PreDestroy //在彻底销毁之前
  12. public void destroy(){
  13. System.out.println("book dao destroy...");
  14. }
  15. }

输出的是

  1. book dao init...
  2. com.chentianyu.service.impl.BookDaoImpl@568bf312
  3. com.chentianyu.service.impl.BookDaoImpl@568bf312

要进行销毁的方式(一种就是关闭容器的方式来做)

  1. public class App
  2. {
  3. public static void main( String[] args )
  4. {
  5. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  6. BookDaoImpl bookDao1 = ctx.getBean(BookDaoImpl.class);
  7. BookDaoImpl bookDao2 = ctx.getBean(BookDaoImpl.class);
  8. System.out.println(bookDao1);
  9. System.out.println(bookDao2);
  10. ctx.close();
  11. }
  12. }
  1. book dao init...
  2. com.chentianyu.Dao.impl.BookDaoImpl@568bf312
  3. com.chentianyu.Dao.impl.BookDaoImpl@568bf312
  4. book dao destroy...

总结

  • bean作用范围
    • @Scope
  • bean的生命周期
    • @PostConstruct (构造方法后)
    • @PreDestroy (销毁前)