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

Spring4 学习笔记(1)-入门及 HelloWorld

2015-03-10 00:13 519 查看
该学习笔记对应的视频文件为尚硅谷佟刚老师的《Spring教程》之(视频文件)。

一、Spring 是什么?

Spring 是一个开源框架。

Spring 为简化企业级应用开发而生

使用 Spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能。

Spring 是一个 IOC(DI) 和 AOP 容器框架。

具体描述 Spring:

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

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

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

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

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

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

二、Spring 的模块




具体介绍参看《Spring 开发参考手册》。

三、问候 Spring4 他大爷

1、jar 包引入

commons-logging-1.2.jar(Spring框架依赖它)

spring-beans-4.0.6.RELEASE.jar

spring-context-4.0.6.RELEASE.jar

spring-core-4.0.6.RELEASE.jar

spring-expression-4.0.6.RELEASE.jar

2、写一个 Java 类

[code]package com.liwei.spring;

public class HelloWorld {
    private String name;

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


如果我们不使用 Spring 的容器,我们会这样写代码:

[code]@Test
public void test01(){
    HelloWorld hw = new HelloWorld();
    hw.setName("小朋友");
    hw.hello();
}


我们可以发现,HelloWorld 这个类的对象是我们自己 new 出来的。“小朋友”这个属性值是我们自己 set 进去的。下面我们会看到,在Spring 容器中,这些都是 Spring 容器帮助我们做好的,或许你会觉得很奇怪,但是这种现象真的很有意思。

3、编写 Spring 的核心配置文件






[code]<?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-4.0.xsd"> 
    <bean id="hello" class="com.liwei.spring.HelloWorld">
        <property name="name" value="老人和孩子们"></property>
    </bean>

</beans>


上面的代码在容器中注册了一个 bean,并且为这个 bean 注册了一个属性:“老人和孩子们”。

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

4、编写测试代码

[code]@Test
public void test02(){
    // 1、创建 Spring 的 IOC 容器
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
    // 2、从容器中获取 bean
    HelloWorld bean = (HelloWorld)ctx.getBean("hello");
    // 3、调用方法
    bean.hello();
}




参考资料:图为 eclipse 安装 spring tool suite 插件的方法。



或者我们还可以直接从 Spring 的官网上下载 spring tool suite 这款 IDE 工具。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: