Spring对象创建与依赖注入


首先创建一个Student实体类,它具有以下属性:

private  String name;
private  Address address;
private  String[] book;
private  List<String> hobbys;
private  Map<String,String>card;
private  Set<String>games;
private  String money;
private  Properties info;

下面利用SpringIOC实现:

1.1、在bean中创建对象:

<bean id="student" class="com.demo.pro.Student">
	<!-- 各种属性-->
</bean>

2、对于对象属性的依赖注入:

2.1、普通值注入:
<!--第一种普通值注入-->
<property name="name" value="fatzard"/>
2.2、利用bean注入:
<!--第二种bean注入-->
<property name="address" ref="adress"/>
2.3、数组注入:
<!--数组注入-->
<property name="book">
    <array>
        <value>追风筝的人</value>
        <value>那不勒斯的灯火</value>
    </array>
</property>
2.4、List注入:
<!--List注入-->
<property name="hobbys">
    <list>
        <value>听歌</value>
        <value>敲代码</value>
    </list>
</property>
2.5、map注入:
<!--map-->
<property name="card">
    <map>
        <entry key="id" value="122121212"/>
    </map>
</property>
2.6、set注入:
<!--set-->
<property name="games">
    <set>
        <value>GTA5</value>
        <value>CSGO</value>
    </set>
</property>
2.7、注入空值:

<!--注入空值-->
<property name="money">
    <null/>
</property>
2.8、Properties的注入:

Properties可以存放很多东西,如下所示:

<!--propertoes-->
<property name="info">
    <props>
        <prop key="学号">202000001</prop>
        <prop key="gender"></prop>
        <prop key="username">root</prop>
        <prop key="pass">root</prop>
    </props>
</property>

3、利用p或c命名空间注入

在bean配置头部加上:

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

完整头部:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd">

4、

使用ApplicationContext获取对应的bean

ApplicationContext context =new ClassPathXmlApplicationContext("beans.xml");
Student student=(Student)context.getBean("student");
System.out.println(student.toString());

文章作者: fatzard
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 fatzard !
评论
  目录
本站总访问量