Spring Ioc底层实现

时间:2021-05-24 12:22:22   收藏:0   阅读:0

原理和步骤

  1. Ioc容器的实现主要依赖的是xml解析和Java反射。
  2. 步骤:读取配置文件 -> 将其逐层“剥开”,获取各项属性 -> 通过各属性配合反射生成对象 -> 将其放入容器中,以供调用

具体实现

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private Integer id;
    private String name;
    private Double price;
}
<?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="threeBody" class="per.tan.ioc.Book">
        <property name="id" value="1"/>
        <property name="name" value="《三体》"/>
        <property name="price" value="59.9"/>
    </bean>
</beans>
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.1</version>
</dependency>
public class Test {
public static void main(String[] args) {
   ApplicationContext context = new MyClassPathXmlApplicationContext("spring.xml");
   Book book = (Book) context.getBean("threeBody");
   System.out.println(book);
 }
}
D:\Java_JDK\JDK8\bin\java.exe ...
Book(id=1, name=《三体》, price=59.9)

Process finished with exit code 0
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!