Spring IOC基本使用

使用IOC容器

手动加载jar包

使用手动加载jar包的方式实现,分为三个步骤,现在几乎不用.

  1. 导包
    commons-logging-1.2.jar
    spring-beans-5.2.3.RELEASE.jar
    spring-context-5.2.3.RELEASE.jar
    spring-core-5.2.3.RELEASE.jar
    spring-expression-5.2.3.RELEASE.jar

  2. 写配置
    在这里插入图片描述
    在src下创建ioc.xml:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
       <?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">

    <!-- id : bean的唯一标识,和其他的bean进行区分-->
    <!-- class:表示要创建的bean的完全限定名-->
    <bean id="person" class="bean.Person">
    <!-- name:属性名称,value:属性值-->
    <property name="id" value="1"></property>
    <property name="name" value="zhangsan"></property>
    <property name="age" value="20"></property>
    <property name="gender" value="男"></property>
    </bean>
    </beans>

    测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
       // 容器中的对象,在容器创建完成之前就已经把对象创建好了
    // 下面注释掉最后两行,就会运行person的无参构造方法
    public class MyTest {
    public static void main(String[] args) {
    // Person person = new Person();
    // person.setAge(20);...
    /**
    * ApplicationContext表示IOC容器的入口。想要获取对象的话必须要创建该类。
    * 该类有两个读取配置文件的实现类:
    * ClassPathXmlApplicationContext:从classpath中读取数据;(用得多)
    * FileSystemXmlApplicationContext:从当前文件系统读取数据
    */
    ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
    // 获取对象要进行强转
    // Person person = (Person) context.getBean("person");
    // 不需要强转
    Person person = context.getBean("person", Person.class);
    System.out.println(person);
    }
    }

报错

Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
找不到对应jar包。
解决:
mvnrepository.com 去找到对应的jar包。【commons logging】

使用maven的方式来构建项目

maven简单使用

帮助更方便管理和构建java项目。
maven如何获取jar包
通过坐标:公司/组织(groupId)+项目名(artifactId)+版本(version)组成,可从互联网、本地等多种仓库源获取。

maven仓库分类

  • 本地仓库:本地目录中。如果A项目下载了,B项目会直接从本地加载。
  • 私有仓库:自己公司的仓库
  • 中央仓库:maven默认下载的仓库地址

maven常用命令

构建项目

  1. 创建maven项目
  2. 添加对应的pom依赖

注意:

  1. 创建对象给属性赋值的时候是通过setter方法实现的
  2. 对象在IOC容器中存储的时候都是单例的,如果需要多例需要修改属性 ioc.xml中,scope=”prototype”

spring对象的获取及属性赋值方式

  1. 通过bean的id获取
  2. 通过bean的类型来获取对象

反射