spring学习实例之bean的获取

本文通过一个简单的示例介绍了如何使用Spring框架。从搭建环境到创建接口及其实现类,再到配置Spring并进行测试,详细展示了Spring的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很遗憾,在达内培训的时候没有好好学习spring,现在只好重新学习。我不太擅于理论的讲解,所以在这就把我做实验的代码贴出来。
工具:MyEclipse8.0+spring2.0
1、首先新建普通java工程:spring1;
2、添加spring2.0的核心类库。
jar包如下图:
[img]http://dl.iteye.com/upload/attachment/348670/665dcdf3-bb71-3fea-b399-a2cebfe237cf.jpg[/img]
3、新建包结构如下图:
[img]http://dl.iteye.com/upload/attachment/348625/de79ec41-f35b-3f91-9f32-095354ac4976.jpg[/img]

编写Hello接口。该接口有一个sayHello方法。hello.java代码如下:

package hello;

public interface Hello {
public void sayHello();
}


编写Hello的实现类:HelloImpl。实现sayHello方法,可以在控制台打印一句话:hello spring !代码如下:

package hello;

public class HelloImpl implements Hello{
public void sayHello(){
System.out.println("hello spring !");
}
}


配置spring的配置文件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"
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.0.xsd">

<bean id="hello" class="hello.HelloImpl"></bean>
</beans>


编写测试测试类TestHello.java

package test;

import hello.Hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


public class TestHello {
public static void main(String[]args){

/**
* bean有两种获取方式:BeanFactory、ApplicationContext
* BeanFactory
* 缺省延迟实例化bean
* ApplicationContext
* 缺省预先实例化bean
* 3种实现:加载资源的位置不同
* ClassPathXmlApplicationContext
* FileSystemXmlApplicationContext
* XmlWebApplicationContext
*/
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory bf=new XmlBeanFactory(resource);
Hello hello1=(Hello)bf.getBean("hello");
hello1.sayHello();

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello2=(Hello)ac.getBean("hello");
hello2.sayHello();
}
}


运行TestHello.java将在控制台打印如下信息:
hello spring !
hello spring !
注意,因为这个例子没有配置log4j,所以会有两行警告信息,直接无视。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值