spring学习 之helloworld

准备学习spring,每天下班学一点

环境准备

eclipse mar 4.5.1:下载地址

Spring STS 4.5.1插件: 下载地址(可以去http://spring.io/tools/sts/all下载最新版本)

maven 3.3.9(由于我准备使用maven创建spring依赖):下载地址

一.maven 相关基础知识 和环境修改

a.添加环境变量 M2_HOME=C:javaapache-maven-3.3.3

path中追加 %M2_HOME%in;

mvn 常用指令:http://www.cnblogs.com/holly/archive/2013/06/15/3137041.html

修改mvn中央库为oschina: http://maven.oschina.net/help.html

修改eclipse中mvn设置

2.创建基于mvn的spring 工程

a.打开eclipse 新建maven 工程

  b.编辑pom.xml文件

  打开spring 官网http://projects.spring.io/spring-framework/,找到相关配置,添加到pom.xml中,等待eclipse从oschina下载对应jar和source-jar

     

下载完成结果

至此,基于maven的spring环境搭建完成

 3.创建spring之Helloword

    a.介绍工程结构

    HelloWord 类:为即将声明的bean

        Main类:为测试方法

            ApplicationContext.xml:spring bean 定义文件

   b.编写相关代码

   HelloWord

public class HelloWord
{
    private String name;

    public String getName()
    {
        return name;
    }

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

  Application.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="baseModel" class="com.liangpeng.spring.beans.HelloWord">
		<property name="name" value="Spring"></property>
	</bean>
</beans>

  Main

public class Main
{
    public static void main(String[] args)
    {
        @SuppressWarnings ("resource")
        ApplicationContext ioc =new ClassPathXmlApplicationContext("ApplicationContext.xml");
        
        HelloWord hello =ioc.getBean(HelloWord.class);
        
        hello.sayHello();
        
    }
}

  运行Main,会发现spring通过反射在ioc容器中实例化HelloWord,并将hello的name设置为Spring

十一月 18, 2015 8:31:06 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6193b845: startup date [Wed Nov 18 20:31:06 CST 2015]; root of context hierarchy
十一月 18, 2015 8:31:06 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [ApplicationContext.xml]
hello:Spring
原文地址:https://www.cnblogs.com/moonblog/p/4970233.html