Spring 学习之 IOC

本文详细介绍了如何使用Spring框架创建一个简单的接口和其实现类,并通过配置文件实现类的注入,最终通过测试类验证实现类是否正确运行。

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

1.到Spring 官方去下砸jar包

spring-framework-4.0.0.M2-dist.zip

2.创建java项目并考入Spring的jar包


注:如是spring3.0之前 只需要spring-*.jar和commons-logging.jar就够了


创建接口

public interface Zoology {
	void run();
}
创建实现类

public class Horse implements Zoology, Serializable {
	private static final long serialVersionUID = 6002695276088191136L;

	@Override
	public void run() {
		System.out.println(getClass().getName()+"==>Run");
	}

}


在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" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  

       <bean id="horse" class="com.spring.service.impl.Horse" />  
</beans>  


创建测试类

package com.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.service.Zoology;

public class TestAop {

	@Test
	public void t(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Zoology zoology = (Zoology)applicationContext.getBean("horse");
		zoology.run();
	}
	
}



运行结果:

十一月 08, 2014 12:11:08 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@97b7b1: startup date [Sat Nov 08 00:11:08 CST 2014]; root of context hierarchy
十一月 08, 2014 12:11:08 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
com.spring.service.impl.Horse==>Run








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值