Spring Demo例子详解
Intellij IDEA的安装
Intellij IDEA要使用旗舰版,旗舰版网上有很多激活方法就不赘述了。我使用的版本为Ultimate 2018.2
新建Spring工程
新建Spring工程,project命名为spring-lihuijuan。
勾选 Create empty spring-config.xml
生成的project如下:
其中lib目录下已经自动下载好了我们需要的jar包
spring-config.xml中的内容如下图所示:
新建一个Bean类
首先创建一个com.lihuijuan.spring.beans.HelloWorld类,有一个studentName属性,还有一个sayHello的方法,还有一个setter方法用来设置studentName属性。
在编辑框中右击鼠标,点击generate,即可自动生成setter和getter方法
package com.lihuijuan.spring.beans;
public class HelloWorld {
private String studentName;
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
public void sayHello(){
System.out.println("Hello"+" "+studentName);
}
}
-
- 创建一个HelloWorld的实例对象
-
- 设置实例对象的name属性
-
- 调用对象的sayHello()方法
public static void main(String[]args){
//不使用Spring框架之前的步骤
//1.创建一个HelloWorld的对象
HelloWorld helloWorld = new HelloWorld();
//2.为实例对象的属性赋值
helloWorld.setStudentName(“lihuijuan”);
//3.调用对象的方法
helloWorld.sayHello();}
执行该main方法,输出为Hello lihuijuan
利用Spring IOC调用 Bean
接下来我们就要使用Spring了
首先在Spring的配置文件中加入如下内容。
public static void main(String[]args){
//使用Spring框架后
//1.创建Spring IOC 容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
//2.通过IOC容器对象来得到Helloworld对应的对象,利用bean id来唯一标识这个对象
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloWorld");
//3.调用sayHello()方法
helloWorld.sayHello();
}
执行一下该main方法,可以得到结果如下:
Spring调用Bean的流程
为了便于分析,我们将HelloWorld中的构造方法和setter方法打印输出,如下:
public class HelloWorld {
private String studentName;
public HelloWorld(){
System.out.println("Constructor...");
}
public void setStudentName(String studentName) {
this.studentName = studentName;
System.out.println("setStudentName...");
}
public String getStudentName() {
return studentName;
}
public void sayHello(){
System.out.println("Hello"+" "+studentName);
}
}
这时候再执行main方法,结果如下:
)