spring学习笔记一

这里记录一个最简单的spring工程,该功能的作用通过ClassPathXmlApplicationContext获取spring配置文件中定义的bean,其中spring的版本是3.0.5.RELEASE,下面介绍工程里面核心的内容。

依赖的jar

spring学习笔记一

其中,core、beans、context是核心jar,logging、asm、expression在核心jar中有引用到。

spring配置文件

<?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.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
	<bean id="kenny" class="service.impl.Juggler" />

	<bean id="duck" class="service.impl.Juggler" >
		<constructor-arg value="15" />
	</bean>
	
</beans>

其中,注意spring3以下和spring3+的配置文件头部分的命名空间的声明是有区别的,这里指简单定义了两个bean。

获取bean

public static void main(String[] args)throws Exception{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("service/impl/spring-idol.xml");
		Performer juggler = (Performer)ctx.getBean("kenny");
		juggler.perform();
		
		Performer duck = (Performer)ctx.getBean("duck");
		duck.perform();
	}
其中,这里注意ClassPathXmlApplicationContext形参的写法,是类资源路。这里通过 ClassPathXmlApplicationContext来加载spring的配置文件。

你可能感兴趣的:(spring,笔记)