bean的属性赋值

1.需要的实体类

Spring(四)--bean的属性赋值-LMLPHP

Spring(四)--bean的属性赋值-LMLPHP

2.需要的配置文件

<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置Grade对应的bean-->
<bean id="grade" class="com.xdf.bean.Grade" c:id="2" c:gradeName="2年级">
<!--01.设值注入 推荐使用 便于阅读
<property name="id" value="1"/>
<property name="gradeName" value="一年级"/>
02. p命名空间注入
p:id="1" p:gradeName="一年级"
03.通过构造方法赋值 必须有对应的构造方法
001.构造方法的参数下标来赋值
<constructor-arg index="0" value="1"/>
<constructor-arg index="1" value="一年级"/>
002.构造方法的参数名称来赋值
<constructor-arg name="id" value="1"/>
<constructor-arg name="gradeName" value="一年级"/>
003.按照默认顺序
<constructor-arg value="一年级"/>
<constructor-arg value="1"/>
04.使用c命名空间
-->
</bean> <!--配置 Student对应的bean-->
<bean id="student" class="com.xdf.bean.Student">
<property name="name" value="小黑"/> <!--普通属性-->
<property name="grade" ref="grade"/><!--域属性-->
<property name="names">
<array> <!--数组-->
<value>小黑1</value>
<value>小黑2</value>
</array>
</property>
<property name="list">
<list><!--list集合-->
<value>小黑1</value>
<value>小黑2</value>
</list>
</property>
<property name="set">
<set><!--set集合-->
<value>小黑1</value>
<value>小黑2</value>
</set>
</property>
<property name="map">
<map><!--map集合-->
<entry key="id" value="1"/>
<entry key="name" value="小白"/>
<entry key="address" value="海淀区"/>
</map>
</property>
<property name="properties">
<props><!--properties属性-->
<prop key="id">1</prop>
<prop key="name">小白</prop>
<prop key="address">海淀区</prop>
</props>
</property>
</bean>
</beans>

3.测试类

public class PropertyDemo {

    public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Grade grade= context.getBean("grade", Grade.class);
System.out.println(grade);
}
}

    未完待续!!!我们一起努力!

05-08 15:46