您的位置:首页 > 编程语言 > Java开发

Spring-01-HelloWorld

2016-02-23 14:41 465 查看

4.1.4

1、 简介

  Spring 是一个IOC(DI)和AOP容器框架,是为简化企业级应用开发而生开源框架,使用 Spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能。

  具体描述 Spring:

   轻量级:Spring 是非侵入性的 - 基于 Spring 开发的应用中的对象可以不依赖于Spring 的 API

   依赖注入(DI — dependency injection、IOC)

   面向切面编程(AOP — aspect oriented programming)

   容器: Spring 是一个容器, 因为它包含并且管理应用对象的生命周期

   框架: Spring 实现了使用简单的组件配置组合成一个复杂的应用. 在 Spring 中可以使用 XML 和 Java 注解组合这些对象

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

2、 IOC & DI 概述

IOC(Inversion of Control) — 其思想是反转资源获取的方向。 传统的资源查找方式要求组件向容器发起请求查找资源. 作为回应, 容器适时的返回资源. 而应用了 IOC 之后, 则是容器主动地将资源推送给它所管理的组件, 组件所要做的仅是选择一种合适的方式来接受资源。这种行为也被称为查找的被动形式

DI(Dependency Injection) — IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如: setter 方法)接受来自如容器的资源注入。相对于 IOC 而言,这种表述更直接

3、 HelloWorld

(1)导入 jar 包

包括beans,context,core,expression等核心jar包,还有一个Apache的 logging 日志记录jar包。

(2)Spring 的配置文件

一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件(通常是xml文件), 这些配置文件用于在 Spring IOC 容器里配置 Bean。Bean 的配置文件可以放在 classpath 下, 也可以放在其它目录下。

(3)bean的编写

例如编写一个hello的javabean,代码如下:

public class Hello {

private String hello;

public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public void sayHello(){
System.out.println("hello : " + hello);
}
}


(4)配置文件中的配置

例如在 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
class:bean 的全类名,通过反射的方式在 IOC 容器中创建bean,所以要求Bean中有无参的构造方法
id:标识容器中的bean,id唯一
-->
<bean id="hello" class="ice.mimosa.a_helloworld.Hello">
<property name="hello" value="mimosa"></property>
</bean>
</beans>


(5)main函数的调用

//1. 创建Spring 的 IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 从IOC 容器中获取Bean实例
Hello hello = (Hello) ctx.getBean("hello");
// 注意配置中必须只能有一个该类型bean 的 id
//Hello hello = ctx.getBean(Hello.class);

//3. 调用sayHello()方法
hello.sayHello();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring