1:新建一个项目webdemo。

2:右键项目----MyEclipse-----Add Spring Capabilities打开对话框进行如下配置如下对话框:

Spring开发Helloworld程序(装配bean)! - 刘立 - 707903908的博客

3:单击next如下对话框:

Spring开发Helloworld程序(装配bean)! - 刘立 - 707903908的博客
4:保持默认,然后finish。
5:新建一个包chapter22.
6:新建一个接口HelloService内容如下:
package chapter22;
public interface HelloService {
 public String getGreeting();
}
6:编写接口的实现类如下:
package chapter22;
public class HelloServiceImpl implements HelloService {
 private String greeting;
 public String getGreeting() {
  return "hello" + greeting;
 }
 public void setGreeting(String greeting) {
  this.greeting = greeting;
  System.out.println("设置greeting属性");
 }
}
7:装配JavaBean如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 <bean id="greeting" class="chapter22.HelloServiceImpl">
  <property name="greeting">
   <value>Michael Jackson</value>
  </property>
 </bean>
</beans>
8:编写测试装配的Bean如下:
package chapter22;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class FirstSpring {
 public static void main(String[] args){
  ApplicationContext context = new FileSystemXmlApplicationContext("src/applicationContext.xml");
  HelloService hello = (HelloService)context.getBean("greeting");
  System.out.println(hello.getGreeting());
 }
}
9:运行测试类,产生结果如下:
设置greeting属性
helloMichael Jackson
 
OVER……
 
结束语:
1:装配Bean实际上就是通过Spring的XML配置文件来建立实现类(Bean类)的对象实例(也成为装配bean)。
2:每一个JavaBean都对应着一个<bean>标签。其中id属性是给这个JavaBean起的别名。
3:整个Spring框架的核心就是装配Bean,通过装配Bean可以有效的使代码得到复用。
posted on 2013-07-02 10:55  裴银祥的博客园  阅读(216)  评论(0编辑  收藏  举报