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方法中添加打印,自行进行验证。
文章内容参考尚硅谷视频