Spring5~HelloWorld

使用Spring5的基本原始步骤:

      ①导入jar包

             

     ②编写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">

	<bean id="helloWorld" class="cn.xmddop.hello.HelloWorld">
		<property name="username" value="will"/>
	</bean>
</beans>

      ③编写javaBean和测试类

package cn.xmddop.hello;

public class HelloWorld {
	private String username;

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
	public void sayHello(){
		System.out.println("欢迎来到Spring5的世界," + username);
	}
}
package cn.xmddop.hello;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class App {

	//传统方式:正控,调用者手动调用对象,创建对象依赖的对象,并组装依赖关系
	@Test
	void test1() throws Exception {
		//创建一个对象
		HelloWorld dao = new HelloWorld();
		//给当前的对象设置一个依赖属性
		dao.setUsername("will");
		dao.sayHello();
	}
	
	//Spring框架
	@Test
	void test2() throws Exception {
		HelloWorld world = null;
		//-----------------------------
		//1:从classpath路径去寻找配置文件,创建资源对象
		Resource resource = new  ClassPathResource("applicationContext.xml");
		//2:根据资源对象,创建Spring Ioc容器对象
		BeanFactory factory = new XmlBeanFactory(resource);
		//3:从Spring Ioc容器对象获取指定名称的对象
		world = (HelloWorld) factory.getBean("helloWorld");
		world.sayHello();
	}
	
}

      ④推荐学习工具  https://spring.io/tools,此款工具是在eclipse基础上做了增强,增加了Spring相关的工具,用起来和eclipse     一 样,不用担心出现不适应的问题。

猜你喜欢

转载自blog.csdn.net/myCsdn_Xm/article/details/98177568