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

Spring入门之HelloWorld

2016-04-27 01:08 375 查看
1.新建java项目 Spring

2.导入jar包

2.1 到http://www.springsource.org/download下载spring,然后进行 解压缩,在解压目录中找到下面jar文件,拷贝到类路径下

2.2 spring的核心类库 在spring文档的dist下 dist\spring.jar

2.3 引入的第三方类库 都spring文档的lib下lib\jakarta-commons\commons-logging.jar

3.新建java类HelloWorld.java,位于包spring.helloworld下

public class HelloWorld {
public void hello(){
System.out.println("hello world");
}
}


4.在包spring.helloworld下新建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-2.5.xsd"> <!--
beans:把一个类放入到spring容器中,此类就称为bean
-->
<!--
一个bean就代表一个类
id就是唯一标识符
-->
<bean id="helloWorld" class="spring.helloworld.HelloWorld"></bean>
</beans>


5.新建测试类HelloWorldTest.java

public class HelloWorldTest {
@Test
public void test(){
/**
* 1.启动spring容器
* 2.从spring容器中把helloWorld对象取出来
* 3.对象.方法
*/
//启动spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring/helloworld/applicationContext.xml");
HelloWorld helloworld = (HelloWorld) context.getBean("helloWorld");
helloworld.hello();
}
}


6.运行test方法,可以得到如下结果:

hello world


还可以在applicationContext.xml中为java类配置别名,比如:

<alias name="helloWorld" alias="不倒翁"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring helloworld