Spring框架--实现使用配置文件控制对象的生成

  Spring框架的学习1--实现使用配置文件控制对象的生成

MyEclipse环境

新建一个Java Project,配置Spring3.1版本,在src目录下默认增加applicationContext.xml文件

运行步骤:

1)在com.etc.service下新建一个类HelloService.java

package com.etc.service;
public class HelloService {
	public void sayHello()
	{
		System.out.println("hello spring");
	}
}

2)在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-3.1.xsd"
	>
	<bean name="hello" class="com.etc.service.HelloService"></bean>
</beans>

3)右键工程名,新建一个test源文件夹,在文件夹下新建一个com.etc.service包,在这个包下新建          HelloServiceTest.java类

package com.etc.service;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloServiceTest {
	@Test
	public void test1()
	{
		//1.配置applicationContext.xml文件
		ClassPathXmlApplicationContext context = 
			new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		HelloService hello = (HelloService) context.getBean("hello");
		hello.sayHello();
	
	}
}

4)运行结果

hello spring

如果不使用Spring框架,在HelloServiceTest.java中的实现代码如下:

HelloService myService = new HelloService();
myService.sayHello();

代码现在看起来虽然简单,但是两个类之间存在依赖关系。之后随着代码的增加,Spring写的代码会越来越少。

使用了Spring框架之后,不再是在类中使用new关键字来新建一个对象,而是通过在配置文件中进行相应的

配置来实现。

效果:不需要在测试类中new一个对象,从而生成一个对象,增加他们之间的依赖性,只需要在Spring的

配置文件中设置bean标签,就可以实现new的功能,并且没有类之间依赖性的存在。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值