Spring Bean和普通的javaBean没有什么区别,都是pojo对象,在spring中,bean的生命周期分为
1.定义Bean
定义JavaBean
- public class UpperAction{
- String message;
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this .message = message;
- }
- public String execute(String str) {
- // TODO 自动生成方法存根
- return (getMessage()+ " " +str).toUpperCase();
- }
- }
通过spring bean的定义文件 applicationContent.xml将javaBean定义成spring bean
- <? xml version = "1.0" encoding = "UTF-8" ?>
- < beans 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" >
- < bean id = "upper" class = "com.lnie.spring.bean.UpperAction" >
- < property name = "message" >
- < value > Hello </ value >
- </ property >
- </ bean >
- </ 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
一般是通过定义文件中注入初始化
如
- < property name = "message" >
- < value > Hello </ value >
- </ property >
3.使用Bean
定义并初始化之后,可以通过spring上下文或是beanFactory取得bean
- //通过ApplicationContext取得bean
- ApplicationContext atx = new FileSystemXmlApplicationContext( "applictionContext.xml" );
- UpperAction a= (UpperAction)atx.getBean( "upper" );
- //通过BeanFactory取得bean
- Resource re = new ClassPathResource( "applictionContext.xml" );
- BeanFactory beans = new XmlBeanFactory(re);
- UpperAction a = (UpperAction)beans.getBean( "upper" );
- System.out.println(a.execute( "bin" ));
4销毁bean
一旦基于spring(web)的应用停止,spring框架将会将bean实例销毁
到此为止,整个spring bean的生命周期已完整都走了一遍。