Spring—IOC入门

入门IOC

IOC:控制反转,将对象的创建,初始化,销毁都交由spring容器管理,开发者就能从对象的创建中解脱出来,不用new,而是直接问spring容器要,来创建一个简单的IOC例子。

  1. 创建maven工程,引入依赖
 <dependency>
   	<groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.7.RELEASE</version>
 </dependency>

 <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
 </dependency>    

2.创建实体类(@Data注解是get,set,以及toString方法)

@Data
public class Book {
    private Integer id;
    private String name;
    private String address;
}

3.在resources当中创建application.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="book" class="org.youyuan.bean.Book"></bean>   
</beans>

4.创建一个测试类,获取bean

 public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        Book book = (Book) context.getBean("book");
        System.out.println(book);
    }

5.运行结果
在这里插入图片描述
是一个空的Book对象

注意:

  1. bean的id属性与name属性在大多数情况下都没有很大的区别,id是唯一标识,只能有一个,而name可以有多个值。
  2. 加载配置文件出来使用ClassPathXmlApplicationContext,也能使用FileSystemXmlApplication(传的是文件的路径)
  3. 获取bean除了使用id与name获取,还可以通过class获取bean,但是有一定的局限性,如果xml中配置两个类型一样的Bean将无法区分,会发生错误。
 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
 Book bean = context.getBean(Book.class);
发布了25 篇原创文章 · 获赞 0 · 访问量 295

猜你喜欢

转载自blog.csdn.net/qq_42219004/article/details/105150844