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

Spring快速入门示例

2017-05-17 16:24 316 查看

开发环境:

Spring 4.0.0+Myeclipse10+JDK1.7

开发过程:

1、新建一个spring01的java工程,在工程目录下新建一个lib包(或者直接建一个web工程,两个方法均可),将以下包导入到lib中



2、创建com.at.beans包,在包中创建HelloWorld.java类。
package com.at.beans;

public class HelloWorld {

private String name;

public void setName(String name) {
this.name = name;
}

public void hello(){
System.out.println("name " + name);
}
}


3、在src文件夹下面新建一个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-4.0.xsd"> 
<!-- 这里的class是使用反射创建的类对象,相当于HelloWorld helloWorld = new HelloWorld(); -->
<bean id="helloWorld" class="com.at.beans.HelloWorld">
<property name="name" value="spring"></property>
</bean>

</beans>


4、测试运行结果代码。
package com.at.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloWorld {

public static void main(String[] args) {

//1、创建spring的IOC容器对象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

//2、从IOC容器中获取bean实例
HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld");

//3、调用方法
helloWorld.hello();
}
}


5、程序运行结果输出。
五月 17, 2017 4:19:32 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5a874bd3: startup date [Wed May 17 16:19:32 CST 2017]; root of context hierarchy
五月 17, 2017 4:19:32 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
name spring


By luoyepiaoxue2014
微博地址: http://weibo.com/luoyepiaoxue2014 点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring web helloworld