Spring的学习运用
  p8RyuvESu2pg 2023年11月13日 17 0

set注入:设置值注入:spring调用类的set方法,完成属性赋值  

peoperty:name:属性名

                 value:属性值

复杂类的注入

property name:属性名

ref=“bean”的id值

创建项目

Spring的学习运用_spring

导入jar包

Spring的学习运用_spring_02

编写School类和Student类

Spring的学习运用_java_03

Student.java

package cn.lexed.pojo;

public class Student {
	private String name;
	private int age;
	private School sc;//name address
	
	public Student() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public School getSc() {
		return sc;
	}
	public void setSc(School sc) {
		this.sc = sc;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", sc=" + sc + "]";
	}
	
	
}

School.java

package cn.lexed.pojo;

public class School {
	private String name;
	private String address;
	public School() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "School [name=" + name + ", address=" + address + "]";
	}
	
}

编写配置文件

Spring的学习运用_spring_04

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

<bean id="stus" class="cn.lexed.pojo.Student">
<!-- 简单类型 -->
<property name="name" value="张三"></property>
<property name="age" value="20"></property>
<!-- 引用类型 -->
<property name="sc" ref="sch"></property>
</bean>

<bean id="sch" class="cn.lexed.pojo.School">
<property name="name" value="南理工"></property>
<property name="address" value="秦淮区"></property>
</bean>

</beans>

编写测试类

Spring的学习运用_xml_05

TestSpring.java

package cn.lexed.test;

import static org.junit.Assert.*;

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

import cn.lexed.pojo.Student;

public class TestSpring {

	@Test
	public void test() {
		//1.创建Spring容器的对象
		ApplicationContext ac=new ClassPathXmlApplicationContext("app.xml");
		//2.使用getBean方法,getBean(配置文件中bean的id值)
		Student s1=(Student)ac.getBean("stus");
		System.out.println(s1);
	}

}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
p8RyuvESu2pg
作者其他文章 更多