Spring 入门学习二之IOC

今天来学习Spring ioc .

1、spring jar 包导入

在 spring 官网下载开发包 spring-framework-4.2.4.RELEASE,而后导入须要的 jar 包到项目 /lib/ 目录下。java


clipboard.pngspring

2、代码开发

新建一个 'src/cn/sxt/bean/Hello.java'文件apache

package cn.sxt.bean;

/**
 * Created by kaiyiwang on 18/5/22.
 */
public class Hello {
    private String name;

    private void setName(String name){
        this.name = name;
    }

    public void show(){
        System.out.println("hello," + name);

    }
}

新建 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.0.xsd"

              <!-- bean就是Java对象 由Spring来建立和管理 -->
              <bean name="hello" class="cn.sxt.bean.Hello">
              <property name="name" value="张三">
              </bean>
</beans>

三、新建测试文件 Test.java
src/cn/sxt/test/Test.java测试

package cn.sxt.test;

import cn.sxt.bean.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by kaiyiwang on 18/5/27.
 */
public class Test {
    public static void main(String[] args){

        // 解析beans.xml文件,生成管理响应的bean对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        Hello hello = (Hello)context.getBean("hello");

        hello.show();
    }
}

右键 'Run Test.main()' 执行编译该文件,会报出以下错误:this

clipboard.png

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:159)

抛出这样的错误,是由于没有引入commons/logging 包,因此,先到官网 http://struts.apache.org/down... 下载 struts-2.3.34 包, 而后引入 commons-logging-1.1.3.jar'包到项目src`下spa

引入该 jar包后,须要添加为项目库路径,不然在写代码引入方法时,不能自动提示相关的方法
clipboard.pngcode

clipboard.png

点击 OK 便可添加成功。xml

相关文章
相关标签/搜索