Spring 环境搭建

1、导包

2、编写Helloworld程序

1 package cn.test.helloWorld;
2 
3 public class HelloWorld {
4     public void sayHello(){
5         System.err.println("1234567890");
6     }
7 }

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-2.5.xsd">
<!-- 
  beans
       把一个类放入到spring容器中,该类就称为bean
-->
<!-- 
  一个bean就代表一个类
   id就是唯一标识符[推荐命令规则是类的第一个字母小写]
-->
<bean name="helloWorld" class="cn.test.helloWorld.HelloWorld"></bean>

</beans>

 这里也可以使用别名来配置,在bean下面添加:<alias name="helloWorld" alias="bm"/>,在后面的调用中就可以使用别名来调用了。

 4、编写启动客户端

 1 @Test
 2     public void doSomething(){
 3         /*
 4          * 1、启动spring容器
 5          * 2、从spring容器中把helloWorld拿出来
 6          * 3、对象.方法
 7          */
 8         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/applicationContext.xml");
 9         HelloWorld helloWorld=(HelloWorld) applicationContext.getBean("helloWorld");
10         helloWorld.sayHello();
11     }

 使用别名调用:效果相同

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/applicationContext.xml");
HelloWorld helloWorld=(HelloWorld) applicationContext.getBean("bm");
helloWorld.sayHello();

posted @ 2015-01-14 15:59  liuwt365  阅读(132)  评论(0编辑  收藏  举报