spring入门案例

一 引入spring的开发包
1 最小配置
spring.jar:该包把常用的jar都包括。
common-logging.jar:日志包。

二 创建spring的一个核心文件applicationContext.xml
hibernate的核心是hibernate.cfg.xml
struts的核心文件是struts-config.xml
spring的一个核心文件是applicationContext.xml,该文件一般放在src目录下,该文件中要引入xsd文件,可以从给出的案例中拷贝一份。

三 配置bean
<?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:context="http://www.springframework.org/schema/context";
        xmlns:tx="http://www.springframework.org/schema/tx";
        xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd">;
<!-- 在容器文件中配置bean(service/dao/domain/action/数据源) -->
<!-- bean元素的作用是,当我们的spring框架加载时候,spring就会自动的创建一个bean对象,并放入内存
    UserService userSerivce=new UserService();
    userSerivce.setName("韩顺平");
    -->
<bean id="userService" class="com.service.UserService">
    <!-- 这里就体现出注入的概念. -->
    <property name="name">
        <value>韩顺平</value>
    </property>
</bean>
</beans>



四 编写业务类
package com.service;
public class UserService {
    private String name;
    
    private BybService byeService;
    public BybService getByeService() {
        return byeService;
    }
    public void setByeService(BybService byeService) {
        this.byeService = byeService;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public void sayHello(){
        System.out.println("hello "+name );
    }
}



五 测试代码
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.BybService;
import com.service.UserService;
import com.util.ApplicaionContextUtil;
public class Test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //我们先使用传统的方法,来调用UserService的 sayHello方法
//        UserService userService=new UserService();
//        userService.setName("顺平");
//        userService.sayHello();
        
        //我们现在使用spring来完成上面的任务
        //1.得到spring 的applicationContext对象(容器对象)
    
        //UserService us=(UserService) ac.getBean("userService");
        //us.sayHello();
        ((UserService)ApplicaionContextUtil.getApplicationContext()
        .getBean("userService")).sayHello();
    }
}



六 测试结果
hello 韩顺平
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值