Spring------基于xml的DI (一)设值注入、构造注入

本文介绍了Spring框架中依赖注入(DI)的概念,详细讲解了设值注入和构造注入两种方式。设值注入通过setter方法完成属性初始化,构造注入则在构造器中设置依赖关系。通过示例代码展示了不同类型的注入实操。
摘要由CSDN通过智能技术生成

DI的分类

DI:bean实例在调用无参构造器创建了空值对象后,对bean对象的属性进行初始化。初始化是由容器自动完成的,称为注入
注入分为:设值注入、构造注入

设值注入

概念:是指,通过setter方法传入被调用者的实例。这种注入方式简单、直观。
简单类型的设值注入
示例:
Student.java

package com.ba01;

public class Student {
   
	
	private String name;
	private int age;
	
	public Student() {
   
		super();
		System.out.println("student无参数构造方法");
	}
	//setter
	public void setName(String name) {
   
		System.out.println("setName:"+name);
		this.name = name;
	}
	public void setAge(int age) {
   
		System.out.println("setAge:"+age);
		this.age = age;
	}
	//toString
	@Override
	public String toString() {
   
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
}

applicationContext.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">

   
    
    <!-- 声明Student对象 -->
    <!-- 
       DI:依赖注入,给属性赋值。
             简单类型:Spring中把String和java基本数据类型称为简单类型。
       1.设值注入:调用类的set方法完成赋值。 常用方式。
           1)简单类型的设值注入:
         <bean id="xx" class="yyy">
           <property name="属性名" value="简单类型的属性值" />
           <property name="属性名" value="简单类型的属性值" />
           ...
         </bean>
         
     -->
    <bean id="myStudent" class="com.ba01.Student">
    	<property name="name" value="李四"/> <!-- setName() -->
    	<property name="age" value="20"/> <!-- setAge() -->
    </bean>

</beans>

MyTest.java

package com.ba01;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
   


	@Test
	public void test01(){
   
		String configLocation="com/ba01/applicationContext.xml";
		ApplicationContext ctx  = new ClassPathXmlApplicationContext(configLocation);
		Student student = (Student) ctx.getBean("myStudent");
		System.out.println("student:"+student.toString()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值