1 Spring4 之环境搭建和HelloWorld

1 Spring 是什么?

  • 具体描述 Spring:
    • 轻量级Spring 是非侵入性的- 基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API
    • 依赖注入(DI --- dependency injection、IOC)
    • 面向切面编程(AOP --- aspect oriented programming)
    • 容器: Spring 是一个容器, 因为它包含并且管理应用对象的生命周期
    • 框架: Spring 实现了使用简单的组件配置组合成一个复杂的应用. 在 Spring 中可以使用 XML 和 Java 注解组合这些对象
    • 一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库 (实际上 Spring 自身也提供了展现层的 SpringMVC 和 持久层的 Spring JDBC)

Spring模块图:

Eclipse开发Spring时需要安装spring插件:springsource-tool-suite-3.6.3.RELEASE-e4.4.1-updatesite.zip(下载链接:http://spring.io/tools/sts/all 需要翻墙)。

2 安装 Eclipse插件

Eclipse—->help—> install new software : 点击Add按钮 ,再点击Archive 选择你刚刚下载的zip文件,这里选择 后面带 spring IDE的四项,并把Contact all updatesite….前面的勾去掉(这个是联网更新),一直点点击 下一步, 最后重启eclipse即可

3 搭建Spring开发环境

    新建Java工程 :命名spring-1;并新建Folder 命名为lib(放Spring基本的jar包)

在lib中导入:commons-logging-1.1.3.jar在struts的lib中可以找到,其余四个都在spring-framework-4.1.2.RELEASE的libs文件夹下,记得将lib下的jar包add Build Path;

    

4 项目结构图:

其中HelloWorld.java

package com.bai.spring.beans;

public class HelloWorld {

    private String name;

    public void setName(String name){

        this.name=name;

    }

    public void hello(){

        System.out.println("hello:"+name);

    }

}

在src下新建spring配置文件,命名为applicationcontext.xml

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 -->

    <bean id="helloworld" class="com.bai.spring.beans.HelloWorld">

        <property name="name" value="Spring"></property>

    </bean>

</beans>

Main.java

package com.bai.spring.beans;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String []args){

        /*    不使用springde 情况

         * //创建一个HelloWorld对象

        HelloWorld helloworld=new HelloWorld();

        //为对象赋值

        helloworld.setName("baixl");

        //调用hello()方法

        */

        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationcontext.xml");

        HelloWorld helloworld=(HelloWorld) ctx.getBean("helloworld");

        helloworld.hello();

    }

}

运行结果:

原文地址:https://www.cnblogs.com/baixl/p/4138717.html