(1)Spring学习记录---Spring_HelloWorld

1、Spring框架简介

Spring是一个开源框架,Spring是在2003年兴起的一个轻量级的开源框架,由Rod johnson创建。主要对JavaBean的生命周期进行管理的轻量级框架,Spring给JavaEE带来了春天。

2、Spring框架特点

√ 轻量级:不是说他的文件大小很小,指的Spring是非侵入性。
  知识点:轻量级框架和重量级框架的区别
      轻量级和重量级的框架是以启动程序所需要的资源所决定,比如EJB在启动程序的时候需要消耗大量的资源,内存和CPU,所以是重量级。
√ 依赖注入:IOC(DI)和面向切面编程:AOP
√ 容器:Spring是一个容器,因为它包含并且管理应用对象的生命周期
√ 框架:Spring实现了使用简单的组件配置组合成一个复杂的应用。
√ 一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库

3、Spring架构

Test:Spring支持Junit单元测试
Core Container(核心容器):里面能看到有4个核心的内容,也就是如果需要使用Spring,这4个jar包是绝对不能少的。
  ① spring-beans-4.3.6.RELEASE.jar (Beans):Bean工厂,创建对象
  ② spring-core-4.3.6.RELEASE.jar (Core):核心的基础
  ③ spring-context-4.3.6.RELEASE.jar(Context):上下文ApplicationContext
  ④ spring-expression-4.3.6.RELEASE.jar(SpEL:Spring的EL表达式)
  知识点:还有一个jar包也是必须的,因为Spring使用了它
  ⑤ commons-logging-1.2.jar
AOP:面向切面编程
Transactions:声明式事务
ORM、JDBC:可以整合hibernate和mybatis
Web、Servlet:可以整合Stucus2和Spring MVC

4、创建一个HelloWorld项目

我用的是myeclipse,创建的是一个javaweb项目

(1)导入jar包

(2)创建一个helloworld.class文件

public class HelloWorld {
	private String name;

	public void setName(String name) {
		this.name = name;
	}
	
	public void sayHello() {
		System.out.println("hello:"+name);
	}
}

(3)创建一个配置文件applicationContext.xml

    <bean name="helloworld" class="jjh.test.HelloWorld">
		<property name="name" value="jjh"></property>
	</bean>

(4)创建一个main.class(主函数入口)

public static void main(String[] args) {
		// 1、创建Spring的IOC容器的对象
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		// 2、从IOC的容器中获取Bean的实例
		HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloworld");
		// 3、调用hello方法
		helloWorld.sayHello();
	}

输出结果

思考一下,如果上面main里的方法我把获取Bean的实例和调用hello方法的都注释掉(即把2和3的全注释掉),那么结果应该是什么?
输出结果:
  初始化构造器
  调用了设置属性

 

测试:

在HelloWorld.class的构造器里打印一句话

public HelloWorld() {
		System.out.println("runing...");
	}

注释掉

结果

验证结果: 说明了在创建SpringIOC容器的时候,就已经对类进行了实例化并对属性进行了赋值

猜你喜欢

转载自blog.csdn.net/ck784101777/article/details/82985964