1. Spring 环境搭建

通过IoC容器来创建对象

  • 搭建Spring环境,添加依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>
  • 创建IoC配置文件,可以自定义名称,spring.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
">

    <bean id="student" class="com.devlin.entity.Student"></bean>

</beans>
  • 调用API获取IoC创建好的对象。

//加载spring.xml配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//获取IoC中的对象
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);

注意,通过IoC容器来管理对象时,对象对应的实体类必须有无参构造函数,否则IoC无法实例化对象,因为IoC底层是通过反射机制来创建对象的,反射机制默认调用实体类的无参构造函数。

Last updated

Was this helpful?