spring学习起步

时间:2023-03-09 16:08:39
spring学习起步

1、搭载环境

spring学习起步

去spring官网下载这几个包,其中commons-logging-1.2.jar是一个日志包,是spring所依赖的包,可以到apache官网上下载

也可以访问http://download.****.net/detail/qq_34615529/9650514进行下载

下载后,将5个包放在工程的lib文件夹下,如果没有lib就自己建一个,然后选中包右键build path

使用eclipse进行spring开发需要一款插件,使用spring官网上提供的springsource-tool-suite进行下载,安装,安装方法参考我的博客

http://www.cnblogs.com/windseek/p/5947205.html

2、运行第一个实例

在src文件夹下面新建三个文件

helloworld.java,main.java,applicationContext.xml

对应的目录如下:

spring学习起步

Helloworld.java

/**
* Project Name:spring
* File Name:Helloworld.java
* Package Name:com.windseek.spring.bean
* Date:2016年10月11日上午11:32:27
* Copyright (c) 2016, windseek
*/ package com.windseek.spring.bean;
/**
* ClassName:Helloworld <br/>
* Function: TODO ADD FUNCTION. <br/>
* Date: 2016年10月11日 上午11:32:27 <br/>
* @author yanglongfei
* @version
* @since JDK 1.6
* @see
*/
public class Helloworld {
private String name;
public void setName(String name){
this.name = name;
System.out.println("hello world");
System.out.println(name);
}
public void hello(){
System.out.println("111");
}
}

  

main.java

/**
* Project Name:spring
* File Name:main.java
* Package Name:com.windseek.spring.bean
* Date:2016年10月11日上午11:35:18
* Copyright (c) 2016, windseek.
*
*/ package com.windseek.spring.bean; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* ClassName:main <br/>
* Function: TODO ADD FUNCTION. <br/>
* Date: 2016年10月11日 上午11:35:18 <br/>
* @author yanglongfei
* @version
* @since JDK 1.6
* @see
*/
public class main {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// Helloworld helloworld = (Helloworld) ctx.getBean("helloword");
// helloworld.hello();
}
}

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="helloword" class="com.windseek.spring.bean.Helloworld">
<property name="name" value="windseek"></property>
</bean>
</beans>

运行结果:  

十月 11, 2016 2:01:43 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@70181c87: startup date [Tue Oct 11 14:01:43 CST 2016]; root of context hierarchy
十月 11, 2016 2:01:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
hello world
windseek

分析,在xml里面配置bean,指定对应的类,然后属性propetty里面传入需要的变量,set后的名字

在main.java里面获取这个xml然后获取相关的bean,根据getBean(id);

然后指定执行里面的具体方法,在获取这个xml时,会执行指定java里的构造方法(先),和set方法(后)