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

来源:互联网 发布:手机淘宝哪里看直播 编辑:程序博客网 时间:2024/06/13 10:56

  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"?><beansxmlns="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 {@Testpublic 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
原创粉丝点击