day01-Spring的maven配置和set注入

  1. 在maven中添加依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>
  1. 在src/main/resouces目录下创建Spring的配置文件,名子一般为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">
</beans>
  1. 创建需要的类,里面要有成员变量的set方法

// Student类
public class Student {
    private String name;
    private int age;
    private School school;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSchool(School school) {
        this.school = school;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", school=" + school +
                '}';
    }
}

// School类
public class School {
    private String name;
    private String address;

    public void setName(String name) {
        this.name = name;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}
  1. set注入,在spring配置文件中添加bean标签

<bean id="myStudent" class="club.soulhotel.Student">
	<property name="age" value="21"/>
    <property name="name" value="令狐冲"/>
    <property name="school" ref="mySchool"/>
</bean>

<bean id="mySchool" class="club.soulhotel.School">
    <property name="name" value="华山派"/>
    <property name="address" value="华山"/>
</bean>
  1. 测试,让Spring自动帮我们创建对象

String config = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) context.getBean("myStudent");
System.out.println(myStudent);
  1. 总结

在使用set注入时,注意基本数据类型和引用数据类型如何注入。
set注入本质上是去调用javaBean类中我们写的set方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值