Spring_2 IOC 入门示例

IOC 工程配置步骤

  1. 引入 jar 包
    这里引入的jar 只是实习 IOC 功能,实际还有许多jar 需要引入。
包名
commons-logging-1.1.3.jar
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
  1. 在src目录下创建beans,xml 文件,并对配置schema 文件(可在帮助文档中和示例中找到)
<?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.xsd">
    
</beans>
  1. 创建实体类
    这个实体类要在 beans.xml 中进行配置
package com.sfox.bean;

public class UserBean {
    public void add(String flg){
        System.out.println("add......." + flg);
    }
}

  1. 在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.xsd">
    
    <bean id="userBean" class="com.sfox.bean.UserBean"/>
</beans>
  1. 最会使用junit 进行测试
    创建一个测试类,在使用junit测试时,我们首先要确认工程中要引入junit 的jar。
    我们在该测试类中使用ApplicationContext加载配置的beans.xml文件。
    在下面的代码中使用@Test注解
    注意下面示例代码中包得引入路径
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sfox.bean.UserBean;

public class TestIop {
    
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserBean user = (UserBean) context.getBean("userBean");
        user.add("bean");
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,860评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,126评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,534评论 18 399
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 9,762评论 2 7
  • 一. Java基础部分.................................................
    wy_sure阅读 9,287评论 0 11

友情链接更多精彩内容