Spring Bean相关操作
spring中两个最基本、最重要的包org.springframework.beans 和 org.springframework.context。为了实现无侵入式的框架,这两个包中大量使用了java中的反射机制。
最重要的两个类
BeanFactory------->先进的配置机制管理任何种类的Bean
ApplicationContext-------->建立在BeanFactory之上,并增加了例如支持国际化、获取资源、事件传递等功能
Bean的配置
<bean id="life" init-method="init" destroy-method="destroy" scope="prototype" class="SpringLifeCycle"/>
public class SpringLifeCycle { public SpringLifeCycle(){ System.out.println("SpringLifeCycle"); } //定义初始化方法 public void init(){ System.out.println("init..."); } //定义销毁方法 public void destroy(){ System.out.println("destroy..."); } public void sayHello(){ System.out.println("say Hello..."); } }
<bean id="hellostaticfac" factory-method="getInstances" lazy-init="true" class="HelloStaticFactory"/>
public class HelloStaticFactory { public HelloStaticFactory(){ System.out.println("HelloStaticFactory constructor"); } //静态工厂方法 public static Test getInstances(){ return new Test(); } }
depends-on:可以用来在初始化使用这个Bean之前,强制执行一个或者多个Bean的初始化。
Bean初始化:
1.配置文档中 配置init-method属性(推荐使用)
2.实现org.springframework.bean.factory.InitializingBean接口(会自动执行 afterPropertirsSet()方法进行属性初始化,不推荐使用,未解耦spring)
Bean的使用:
1.使用BeanWrapper
HelloWorld hw = new HelloWorld();
BeanWrapper bw = new BeanWrapperImpl(hw);
bw.setPropertyValue("msg","hello world!");
System.out.println(bw.getPropertyValue("msg"));
2.使用BeanFactory
InputStream is = new FileInputStream("config.xml");
XmlBeanFactory fac = new XmlBeanFactorty(is);
HelloWorld hw = (HelloWorld)fac.getBean("HelloWorld");
System.out.println(hw.getMsg());
3.使用ApplicationContext
ApplicationContext ac = new FileSystemXmlApplicationContext("config.xml");
HelloWorld hw = (HelloWorld)ac.getBean("HelloWorld");
System.out.println(hw.getMsg());
Bean的销毁
1.配置文件中指定 destroy-method
2.实现org.springframework.bean.factory.DisposableBean接口(自动执行destory())
ref属性指定bean的 三种模式
1.local
local必须与bean的id一致,在同一个xml 中如果没有匹配元素,xml解析器将会产生一个错误,如果一个bean与被引用的bean在同一个xml中,则用local是最好的选择。
2.bean属性
bean属性最大的优点是 被引用的bean可以不在同一个xml中。bean属性的值可以与被参考引用的bean的id属性相同,也可以与name属性相同。
3.parent
各位看官自己查文档了解即可,不常用,我也没看懂啥意思就不写了