> 文档中心 > Spring注解开发 - bean的作用范围、bean的生命周期

Spring注解开发 - bean的作用范围、bean的生命周期

注解开发bean

  • 一、使用@Scope 注解管理bean的作用范围
      • 1、在bean类中加入@Scope 注解
      • 2、编写代码测试@Scope注解是否配置成功
      • 3、测试结果
  • 二、使用注解配置bean的生命周期
      • 1、定义init方法和destroy方法
      • 2、编写测试代码
      • 3、测试结果

一、使用@Scope 注解管理bean的作用范围

1、在bean类中加入@Scope 注解

@Repository("beanDao")@Scope("singleton")public class BeanDaoImpl implements BeanDao {    public void save() { System.out.println("beanDao save...");    }}
  • 不添加@Scope 注解 或者 不使用括号赋值,默认为singleton单例模式。
  • 非单例 赋值为"prototype"。
  • @Scope(“singleton”) 对应的xml代码为
<bean id="beanDao" class="dao.impl.BeanDaoImpl" scope="singleton"/>

2、编写代码测试@Scope注解是否配置成功

public class App {    public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); BeanDao beanDao1 = (BeanDao) context.getBean("beanDao"); BeanDao beanDao2 = (BeanDao) context.getBean("beanDao"); System.out.println(beanDao1); System.out.println(beanDao2);    }}

3、测试结果

dao.impl.BeanDaoImpl@525f1e4edao.impl.BeanDaoImpl@525f1e4e
  • 两个bean对象的地址值是相同的,说明是单例模式,@Scope注解起作用了。

二、使用注解配置bean的生命周期

1、定义init方法和destroy方法

@Repository("beanDao")@Scope("singleton")public class BeanDaoImpl implements BeanDao {    public void save() { System.out.println("beanDao save...");    }    @PostConstruct    public void init() { System.out.println("init...");    }    @PreDestroy    public void destroy() { System.out.println("destroy...");    }}
  • 使用@PostConstruct 注解来标注初始化方法,“PostConstruct"翻译成中文是"构造方法后”,刚好初始化方法就是在构造方法后执行的。
  • 使用@PreDestroy 注解来标注销毁方法,“PreDestroy"翻译成中文是"销毁前”,销毁方法是在销毁前执行。
  • 可以通过分析方法的执行顺序来巧记注解名。

2、编写测试代码

public class App {    public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); BeanDao beanDao = (BeanDao) context.getBean("beanDao"); beanDao.save(); context.close();    }}

3、测试结果

init...beanDao save...destroy...
  • 有关bean的生命周期的详细介绍及xml配置方式可以点击查看文章"Spring - bean的生命周期"。