spring讲解2--进行helloworld输出(基于xml文件的形式)

spring讲解2–进行helloworld输出(基于xml文件的形式)

使用spring 打印 helloWorld

进行spring依赖包的下载

依赖包下载链接 spring 4.0.0
上面的依赖包包括在开发中使用的各种jar包。(下面lib文件中包有的就是使用此链接下的文件)
(1)创建简单的Java工程,创建lib文件夹。
将下面的包导入项目中。(下面的包在链接中可以找到,其中commons-logging 包可以从maven中进行下载)。
在这里插入图片描述
在这里插入图片描述
(2)创建框架的配置文件
src - > new - > other - >spring - > 在这里插入图片描述
创建名字,习惯命名为 : applicationContext.xml,finish。
在这里插入图片描述
(3)创建包,并且创建类HelloWorld
在这里插入图片描述

package com.atspring.beans;

public class HelloWorld {
	private String name ;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "HelloWorld [name=" + name + "]";
	}
}

(4) 使用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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<bean id="" class="com.atspring.beans.HelloWorld">
		<property name="name" value="spring"></property>
	</bean>
</beans>

进行类的配置,其中class后面跟的是类的全类名(使用反射的方式创建对象), 使用反射机制进行对象的创建
Class cls= Class.forName(“com.atspring.beans.HelloWorld”); Object obj = cls.new Instance(); //进行对象的创建 (无参构造方法)
将HelloWorld类或者对象的管理都交给spring容器IOC进行管理。 其中id表示bean的唯一标识, property
是通过set方法给对象属性进行赋值。(其中在类中set方法后面的字符的小写对应property 后面指定的name值

(5) 更改main函数

package com.atspring.test;

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

import com.atspring.beans.HelloWorld;

public class Main {
	public static void main(String[] args) {
		//下面的方式是简单的创建对象的方式进行对象的调用
//		HelloWorld helloWorld = new HelloWorld();
//		helloWorld.setName("spring");
//		System.out.println(helloWorld);
		
		//下面的方式使用spring的方式进行对象的调用(使用反射机制进行对象的创建 IOC)
		//获取ioc容器
		ApplicationContext als = new ClassPathXmlApplicationContext("applicationContext.xml");
		//从IOC容器中找到对应的对象
		Object helloWorld = (HelloWorld)als.getBean("helloWorld");
		//调用方法
		System.out.println(helloWorld.toString());
	}
}

成功执行:
在这里插入图片描述
(6) 验证构造方法和set的方法执行
在helloworld类中,无参构造方法和set方法中添加打印,自行进行验证。

文章内容参考尚硅谷视频

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值