spring-helloworld (1)

关于spring的简介以及说明:开涛的博客对spring的讲解
这里只是spring的使用。 (使用spring4)

一、eclipse安装springsource-tools插件

  • 插件安装方法说明(springsource-tool-suite-3.4.0.RELEASE-e4.3.1-updatesite.zip):

    • 1.Help --> Install New Software...

    • 2.点击 Add...

    • 3.点击, Archive...

    • 4.选择springsource-tool-suite-3.4.0.RELEASE-e4.3.1-updatesite.zip文件,然后点击ok

    • 5.然后选择带有spring IDE的选项。

    • 6.取消勾选右下角的 contact all update sites during...

    • 7.一直点击下一步知道完成。完成之后,会提示重启eclipse (期间最好联网验证一些东西)

  • 插件的好处

    • spring配置文件有提示的功能,且写错的时候,会以报错的方式提示你
    • 被spring创建对象的java文件以及配置文件有s标记

二、新建maven工程,引入spring配置

<!-- spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
<version>4.1.9.RELEASE</version>  

三、添加helloworld类

public class HelloWorld {
    private String user;
    
    public HelloWorld() {
        System.out.println("HelloWorld's constructor...");
    }
    
    public void setUser(String user) {
        System.out.println("setUser:" + user);
        this.user = user;
    }
    
    public HelloWorld(String user) {
        this.user = user;
    }
    public void hello(){
        System.out.println("Hello: " + user);
    }
    
}  

四、使用springsource-tools插件 创建spring配置文件。并使用spring创建helloworld的实例

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    
    <!-- 配置一个 bean -->
    <bean id="helloWorld" class="com.hp.spring.helloworld.HelloWorld">
        <!-- 为属性赋值 -->
        <property name="user" value="Jerry"></property>
    </bean> 
</beans> 

五、编写测试类,测试spring创建的helloworld对象

    public static void main(String[] args) {
        // 传统的方式,使用new方式创建helloworld对象,并设置tom,然后执行hello方法
        // HelloWorld helloWorld = new HelloWorld();
        // helloWorld.setUser("Tom");
        // helloWorld.hello();

        // 使用spring创建helloworld对象
        // 1. 创建 Spring 的 IOC 容器
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        // 2. 从 IOC 容器中获取 bean 的实例
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
        helloWorld.hello(); 
    }  

控制台打印:
HelloWorld's constructor...
setUser:Jerry
Hello: Jerry

整个系列项目代码: http://git.oschina.net/nmc5/spring

原文地址:https://www.cnblogs.com/linhp/p/5881757.html