Spring:快速入门的小例子

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值