要引用已经设置的bean实例,可以使用<ref>
标签
依赖注入(Dependency Injection,简称DI)
使用Spring IDE 可视化bean文件的节点摘要
Bean graph
Bean 消息,事件章
Bean基本管理
Application是基于BeanFactory而建立的。
最常使用的3个,我使用过其中一个
ApplicationContext ac = new ClassPathXmlApplicationContext(“applicationContext.xml”);
ApplicationContext可以读取多个 Bean定义文件
ApplicationContext ac = new ClassPathXmlApplicationContext(new String [] {“applicationContext.xml”,”applicationContext2.xml”});
也可以使用文件的通配符 *
import 也可以导入bean定义文件, 必须在 标签之前
Bean的识别名称 和 别名 ,也就是一个实例可以起多个名字
下面是两种别名的方式, alias 和 name属性
<bean id="helloworld" class="com.kpk.learnSpring.hellobean" name="hell003,hell004">
<property name="helloWorld"><value>fupeng2016</value></property>
</bean>
<alias name="helloworld" alias="hell001"/>
<alias name="helloworld" alias="hell002"/>
Bean的实例化
1,默认构造函数,没有参数
<bean id="helloworld" class="com.kpk.learnSpring.hellobean" />
factory-bean=””
factory-method=”“
Bean的 scope
取得实例默认是 singleton,一个bean名称只维持一个实例。
使用了scope参数,将bean设置为 每一个取bean都产生一个新的实例
<bean id="floppy" class="com.kpk.learnSpring.FloppyWriter" scope="prototype">
使用BeanFactory 在 getBean() 方法调用时,才会实例化对象
而ApplicatoinContext会将所有bean实例化。除非有lazy-init
bean如果定义的太多,也可以使用继承
<bean id="BaseCustomerMalaysia" class="com.mkyong.common.Customer" abstract="true">
<property name="country" value="Malaysia" />
</bean>
<bean id="CustomerBean" parent="BaseCustomerMalaysia">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
Bean的依赖设置
Type3 IoC
有参数的构造函数
<bean id="testTpl" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg index="0" ref="solrServer1" />
<constructor-arg index="1" value="simu" />
</bean>
如果多个构造方法,参数相同时候,可以在配置文件中指定去按照哪个函数去构造。
可以使用value标签,或者value属性
如果将某个属性设置为null ,可以使用null标签。
使用ref标签,可以直接只用某个已经定义的Bean实例,这时必须在同一个设置文件中。 且可以指定local属性
class属性
depend-on属性,可以在实例化本bean之前,先去实例化,depend-on里指定的属性。
自动绑定
autowire=”byType”
autowire=”byName”
autowire=”constructor”
autowire=”autodetect”
不习惯依赖这些自动绑定, 这都是些偷懒的方法,不是必须的。
dependency-check=”all”
一共有四个值可选,simple,objects,all,none