Spring HelloWorld

来源:互联网 发布:表白网站html源码 编辑:程序博客网 时间:2024/05/22 08:12
具体描述 Spring:
轻量级:Spring 是非侵入性的 - 基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API
依赖注入(DI --- dependency injection、IOC)
面向切面编程(AOP --- aspect oriented programming)
容器: Spring 是一个容器, 因为它包含并且管理应用对象的生命周期
框架: Spring 实现了使用简单的组件配置组合成一个复杂的应用. 在 Spring 中可以使用 XML 和 Java 注解组合这些对象

一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库 (实际上 Spring 自身也提供了展现层的 SpringMVC 和 持久层的 Spring JDBC)


传统方式的HelloWorld:

实例化一个HelloWorld类的对象,再对该对象属性进行赋值,最后调用hello()方法。

Spring实现的HelloWorld:

除去了实例化对象和赋值操作,在applicationContext.xml文件中对对象的属性设置值,然后通过容器读取xml文件来实现对象实例化,不需要手动创建对象。

具体代码如下:

HelloWorld.java:

package com.dejun.spring;


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


public class HelloWorld {


private String name;


public void setName(String name) {
this.name = name;
}


public void hello() {
System.out.println("My name is " + name + "!");
}


}

Test.java:

package com.dejun.spring;


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




public class Test {
public static void main(String[] args) {
// HelloWorld helloWorld = new HelloWorld();
// helloWorld.setName("spring");
ApplicationContext applicationContext = 
new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld)applicationContext.getBean("helloWorld");
helloWorld.hello();
}
}


xml中配置bean:

class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参数的构造器

id:标示容器中的bean,id唯一

在Spring IOC 容器读取Bean配置创建Bean实例之前,必须对它进行实例化,只有在容器实例化以后,才可以从IOC容器里获取Bean实例并使用。Spring提供了两种类型的IOC容器实现:

BeanFactory:IOC容器的基本实现;

ApplicationContext:提供了更多高级的特性,是BeanFactory的子接口。

BeanFactory是Spring框架的基础设施,面向Spring本身;ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用ApplicationContext而非底层的BeanFactoty。

ApplicationContext 的主要实现类:
ClassPathXmlApplicationContext:从 类路径下加载配置文件
FileSystemXmlApplicationContext: 从文件系统中加载配置文件
ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() 和 close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力
ApplicationContext 在初始化上下文时就实例化所有单例的 Bean。
WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作。


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 = "com.dejun.spring.HelloWorld">
<property name="name" value ="Spring" >
</property>
</bean>
</beans>

1 0
原创粉丝点击