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
- Spring框架--实现使用配置文件控制对象的生成
- spring 框架的配置文件
- 浅谈spring+springMVC+mybatis框架整合(配置文件的使用)
- Spring使用环境变量控制配置文件加载
- spring 框架中的依赖注入(IOC--设值注入)---使用xml简单配置文件---的具体实例的简单实现
- Spring配置文件的使用
- 使用Spring配置文件实现AOP
- 使用Spring配置文件实现事务管理
- 使用Spring配置文件实现AOP
- 使用spring配置文件实现AOP
- 使用Spring配置文件实现AOP
- 使用Spring配置文件实现AOP
- 使用Spring配置文件实现事务管理
- spring aop实现过程之一代理对象的生成
- .NET 插件系统框架设计(二) 使用对象序列化实现自定义配置文件管理
- Spring原理之通过反射+配置文件生成对象池
- 利用Xdoclet生成spring的配置文件
- xdoclet配置自动生成spring的配置文件
- iOS TheOperationCouldn'tbeCompleted
- Spring框架 AOP(三)
- opencv学习(1)——读入并显示一幅图片
- jQuery Mobile基础学习(1)
- 输出++++++
- Spring框架--实现使用配置文件控制对象的生成
- PHP自增(++)中的一些奇葩问题研究记录
- ACM-1019
- php面向对象程序设计(OOP)的61条准则
- 怎样实现下拉合作网站登录界面
- JBOSS简单的认识
- ffmpeg基本用法
- java 位置运算
- 简单的侧滑