Spring:快速入门的小例子

来源:互联网 发布:阿里云 ddns 编辑:程序博客网 时间:2024/06/05 03:11

Spring是什么?
struts是web框架(jsp/action/actionform)
hibernate是orm框架,处于持久层
spring是容器框架,用于配置bean,并且维护bean之间关系的框架。

spring中的一些概念:
bean:表示java中的任何一种对象,javabean/servive/action/数据源
ioc:控制反转 inverse of control
di:依赖注入dependency injection

spring不仅可以用在java web程序中还可用在java本地程序中,以下用一个实例来体现出spring的作用

普通的java程序:

public class UserService {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void sayHello(){        System.out.println("hello"+name);    }}
public static void main(String[] args) {//先使用传统的方法来调用UserService的sayHello方法    UserService userService = new UserService();    userService.setName("黄河大侠");    userService.sayHello();}

结果输出:hello黄河大侠

现在使用spring框架来实现同样的效果

1.首先引入jar包:这里只引入两个jar包:spring.jar和common-logging.jar

2.编写ApplicationContext.xml文件,该文件放在src目录下

<?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.5.xsd            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">    <!--  在容器文件中配置bean(service/dao/domain/action/数据源)-->            <!--  bean元素的作用是,当我们的spring框架加载的时候,spring就会自动的创建一个bean对象,并放入内存,相当于如下操作            UserService us= new UserService();            us.setName("黄河大侠");            spring是如何实现的?就是利用的反射机制    -->    <bean id="us" class ="wade.service.UserService">        <!-- 这里就体现出了注入的概念,把属性的值注入到了bean中,目标类中必须要对应属性的set方法-->        <property name="name">            <value>黄河大侠</value>        </property>    </bean></beans>

3.写测试代码测试

public static void main(String[] args) {    //我们现在使用spring来完成上面的任务    //1.得到Spring的applicationContext对象    ApplicationContext ac=         new ClassPathXmlApplicationContext("applicationContext.xml");        //2.得到我们需要的对象。这里“us”和配置文件中bean的id属性值对应        UserService us=(UserService)ac.getBean("us");        us.sayHello();    }}

结果输出:hello黄河大侠

补充:spring的xml文档检查文件不再是DTD文件,而是xsd文件

0 0
原创粉丝点击