Spring Bean

本文详细介绍了Spring框架中Bean的生命周期,包括定义、初始化、使用及销毁等阶段,并提供了具体的JavaBean示例和Spring配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Bean和普通的javaBean没有什么区别,都是pojo对象,在spring中,bean的生命周期分为

1.定义Bean

定义JavaBean

  1. public   class  UpperAction{
  2.     
  3.     String message;
  4.     
  5.      public  String getMessage() {
  6.          return  message;
  7.     }
  8.      public   void  setMessage(String message) {
  9.          this .message = message;
  10.     }
  11.      public  String execute(String str) {
  12.          // TODO 自动生成方法存根
  13.          return  (getMessage()+ " " +str).toUpperCase();
  14.     }
  15. }

通过spring bean的定义文件 applicationContent.xml将javaBean定义成spring bean

  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>
  2. < beans   xmlns = "http://www.springframework.org/schema/beans"
  3.      xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  4.      xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" >
  5.      < bean   id = "upper"   class = "com.lnie.spring.bean.UpperAction" >
  6.          < property   name = "message" >
  7.              < value > Hello </ value >
  8.          </ property >
  9.      </ bean >
  10. </ beans >

spring bean 定义文件中的DTD为,

xmlns="http://www.springframework.org/schema/beans "
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd "

必不能错,当然spring版本不一样可能xsd版本也会不一样

2.初始化Bean

一般是通过定义文件中注入初始化

  1. < property   name = "message" >
  2.              < value > Hello </ value >
  3.          </ property >

3.使用Bean

定义并初始化之后,可以通过spring上下文或是beanFactory取得bean

  1. //通过ApplicationContext取得bean 
  2. ApplicationContext atx =  new  FileSystemXmlApplicationContext( "applictionContext.xml" );
  3. UpperAction a= (UpperAction)atx.getBean( "upper" );
  4.         
  5. //通过BeanFactory取得bean 
  6. Resource re =  new  ClassPathResource( "applictionContext.xml" );
  7. BeanFactory beans =  new  XmlBeanFactory(re);
  8. UpperAction a = (UpperAction)beans.getBean( "upper" );
  9. System.out.println(a.execute( "bin" ));

4销毁bean

一旦基于spring(web)的应用停止,spring框架将会将bean实例销毁

 

到此为止,整个spring bean的生命周期已完整都走了一遍。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值