Spring开发Helloworld程序(装配bean)!

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可以有效的使代码得到复用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值