spring环境搭建与测试

18 篇文章 0 订阅
9 篇文章 0 订阅

Chapter1、搭建与测试spring的环境

1、  将必要的jar包导入到新建的project中(可以去官网下载,也可以google或者百度)至少必须使用的有spring.jar commons-logging.jar

 

2、  calsspath路径下创建配置文件beans.xml(模板到处有)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
          <bean id="" class=""></bean>
</beans>

 

 

 

 3、  实例化spring容器:

   实例化Spring容器的两种方式:

1)在类路径下寻找配置文件来实例化容器

ApplicationContext ctx = new ClassPathXmlApplicationXContext(new String[]{“beans.xml”})

    (2)在文件系统路径下寻找配置文件来实例化容器

ApplicationContext ctx = new FileSystemXmlApplication(new String[]{“d:\\beans.xml”});

Spring 的配置文件可以指定多个,可以通过String数组传入,也可以是一个String

public class Test {

    public static void main(String[] args) {
        //IOC容器实例化
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

    }

}

 

 

 

  运行测试,结果如下:

Spring环境搭建成功!

4、创建业务bean接口

package com.wxy.service;

public interface PeopleService {

    public abstract void save();

}

 

 

5、实现业务bean接口:

package com.wxy.service.impl;

import com.wxy.service.PeopleService;

public class PeopleServiceBean implements PeopleService {

    /* (non-Javadoc)
     * @see com.wxy.service.impl.PeopleService#save()
     */
    public void save() {
        System.out.println("--> the method is called save()!");
    }

}

 

 

 

 

6、  beans.xml中配置业务bean,将bean交给spring容器管理,spring创建和维护该bean,用户使用时,只需要获取就可以了,不用自己创建,实现IoC

依赖倒置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
          <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean"></bean>
</beans>

 

 

 

7、 使用业务bean

public class Test {

    public static void main(String[] args) {
        //IOC容器实例化
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        //获取业务bean
        PeopleServiceBean peopleService = (PeopleServiceBean) ctx.getBean("peopleService");
        peopleService.save();
    }

}

 

 

调用结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值