Spring:xml类型进行值的注入

1.依赖注入之setter注入流程

(1)创建学生类Student(要提供setter方法)

public class Student {
	 private Integer id; 
	 private String name; 
	 private Integer age; 
	 private String sex; 
	 还有setter啥的方法不详细写了
  }

(2)配置bean时为属性赋值

<bean id="studentOne" class="com.atguigu.spring.bean.Student">
	 <!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 --> 
	 <!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关) --> 
	 <!-- value属性:指定属性值 --> 
	   <property name="id" value="1001"></property>
	   <property name="name" value="张三"></property> 
	   <property name="age" value="23"></property>
	   <property name="sex" value="男">
	   </property> </bean>

(3)测试是否在容器中获取的到已经注入过值的对象。

@Test public void testDIBySet(){
 	 ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
 	 Student studentOne = ac.getBean("studentOne", Student.class); 
 	 System.out.println(studentOne); }
2.依赖注入之构造器注入

(1)在Student类中添加有参构造

public Student(Integer id, String name, Integer age, String sex) {
 this.id = id; 
 this.name = name; 
 this.age = age; 
 this.sex = sex; }

(2)配置bean

<bean id="studentTwo" class="com.atguigu.spring.bean.Student"> 
	<constructor-arg value="1002"></constructor-arg> 
	<constructor-arg value="李四"></constructor-arg> 
	<constructor-arg value="33"></constructor-arg> 
	<constructor-arg value="女"></constructor-arg> 
</bean>

(3)测试

@Test public void testDIBySet(){
	  ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
	  Student studentOne = ac.getBean("studentTwo", Student.class); 
	  System.out.println(studentOne); }

3.字面量赋值
4.为类类型属性赋值
4.1方式一 :引用外部已声明的bean
新建一个Clazz的类,然后它作为student的成员变量。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4.2方式二: 内部Bean
在这里插入图片描述
4.3方式三:级联属性赋值
在这里插入图片描述

5.为数组类型属性赋值
在这里插入图片描述

在这里插入图片描述
6.为集合类型属性赋值
在这里插入图片描述
在这里插入图片描述
7.为Map集合类型属性赋值
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值