您的位置:首页 > 编程语言 > Java开发

springframework(二)第一个spring程序

2016-07-29 00:00 501 查看
建立一个简单的javabean实现属性定制的注入,并引入appliationContext.xml文件(这里用bean-config.xml)作为配置文件的概念。

在这里我们使用xmlschema来进行spring的配置文件的描述规则:
开始我们的第一个java程序:

package com.itcast.first;
//第一个使用spring管理的bean,展示依赖注入
public class Hello {
private String helloworld;
public String getHelloworld() {
return helloworld;
}
public void setHelloworld(String helloworld) {
this.helloworld = helloworld;
}
}


编写我们的第一个配置文件,来实现反转控制ioc,依赖注入di:

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">
<!-- 我的第一个依赖注入的bean -->
<bean name="hello" class="com.itcast.first.Hello">
<property name="helloworld">
<value>hello,man</value>
</property>
</bean>
</beans>


编写我们的测试类:

package com.itcast.first;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

//测试程序,测试简单依赖注入
public class TestHello {
private static final Log logger = LogFactory.getLog(TestHello.class);
public static void main(String[] args) {
Resource rs = (Resource) new ClassPathResource("bean-config.xml");
BeanFactory factory = new XmlBeanFactory(rs);
Hello h = (Hello) factory.getBean("hello");
logger.info(h.getHelloworld());
}
}


上边就是我们的第一个spring程序。
关于spring2版本以后,配置文件用xmlschema而不用dtd的原因如下:
注意点:我们的spring的xml schema文件的编写,以及如果使用dtd,那么我们需要做的处理。
我们为什么要使用schema,而放弃dtd来表述我们的配置文件?
因DTD有着不少缺陷:
1) DTD是基于正则表达式的,描述能力有限;
2) DTD没有数据类型的支持,在大多数应用环境下能力不足;
3) DTD的约束定义能力不足,无法对XML实例文档作出更细致的语义限制;
4) DTD的结构不够结构化,重用的代价相对较高;
5) DTD并非使用XML作为描述手段,而DTD的构建和访问并没有标准的编程接口,无法使用标准的编程方式进行DTD维护。
而XML Schema正是针对这些DTD的缺点而设计的,XML Schema的优点:
1) XML Schema基于XML,没有专门的语法
2) XML可以象其他XML文件一样解析和处理
3) XML Schema支持一系列的数据类型(int、float、Boolean、date等)
4) XML Schema提供可扩充的数据模型。
5) XML Schema支持综合命名空间
6) XML Schema支持属性组。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: