(二)再识spring之IOC:基于XML实例化和注入Bean的方式介绍
程序员文章站
2022-05-24 17:48:41
...
前述概要:
-
在使用Bean之前,首先我们要导入spring的两个依赖库,如下:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.8.RELEASE</version> </dependency>
-
在resources,添加spring.xml配置文件,抬头如下:
<?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.xsd"> </beans>
一.实例化Bean方式介绍
-
通过构造方法实例化Bean
<bean class="org.mk.model.Bean1" id="bean1"/>
-
通过静态方法实例化Bean
<bean class="org.mk.model.Bean2Factory" factory-method="getBean2" id="bean2"/>
-
通过实例方法实例化Bean
<bean class="org.mk.model.Bean3" factory-bean="Bean3Factory" factory-method="getBean3" id="bean3"/>
-
bean的别名
a.通过 alias标签 实现
b.通过 name属性 实现<bean class="org.mk.model.Bean1" name="bean1_1" id="bean1"/> <alias name="bean1" alias="bean1_2"/>
二.注入Bean方式介绍
-
通过构造方法注入bean
name:类的属性名,index:索引位置 ,type:类型,value:属性值,ref:依赖其他的bean的id<bean class="mk.model.AnotherBean" id="anotherBean"/> <bean class="mk.model.Bean" id="bean"> <constructor-arg index="0" name="anotherBean" type="mk.model.AnotherBean" ref="anotherBean"/> <constructor-arg index="1" name="string" type="java.lang.String" value="bean-string"/> </bean>
-
通过set方法注入bean
<bean class="mk.model.Bean" id="bean"> <property name="anotherBean1" ref="anotherBean"/> <property name="string1" value="bean-string1"/> </bean>
-
集合类Bean的注入(List,Set,Map,Properties)
<bean class="mk.model.Bean" id="bean"> <property name="stringList"> <list> <value>aaaa</value> <value>bbbb</value> </list> </property> <property name="anotherBeansList"> <list> <ref bean="anotherBean"/> <ref bean="anotherBean"/> </list> </property> <property name="stringSet"> <set> <value>aaaa</value> <value>bbbb</value> </set> </property> <property name="anotherBeanSet"> <set> <ref bean="anotherBean"/> <ref bean="anotherBean"/> </set> </property> <property name="stringMap"> <map> <entry key="ccc" value="ddd"/> <entry key="eeee" value="ffff"/> </map> </property> <property name="anotherBeanMap"> <map> <entry key-ref="anotherBean" value-ref="anotherBean" /> <entry key-ref="anotherBean" value-ref="anotherBean" /> </map> </property> <property name="properties"> <props> <prop key="aaaa">bbbb</prop> </props> </property> </bean>
-
null值注入
<bean class="mk.model.Bean" id="bean"> <property name="anotherBean2"> <null></null> </property> </bean>
-
注入时创建内部Bean
<bean class="mk.model.Bean" id="bean"> <property name="anotherBean1"> <bean class="mk.model.AnotherBean"></bean> </property> </bean>