SpringBoot用容器IoC管理Bean

    技术2022-07-10  136

    认识IoC容器和Servlet容器

    认识容器 1.IoC容器 IoC(Invension of Control) 容器,是面向对象编程中的一种设计原则,意思是控制反转。它将程序中创建对象的控制权交给Spring框架来管理,以此来降低代码之间的耦合度。

    在传统编程中,要实现一种功能一般需要几个对象相互引用。在主对象中要保存其他类型对象的引用,以便在主对象中实例化对象,然后通过调用这些引用类的方法来完成任务。

    而IoC容器的作用是什么呢?要使用某个对象,只需要从IoC容器中获取使用的对象,不需要关心对象的创建过程,也就是把创建对象的控制权反转给了Spring框架。

    用IoC管理Bean

    实验结果 运行testIoC方法,在控制台会输出如下结果

    User(id=1, name=lishizheng)

    项目目录 0.添加依赖 该依赖用于测试,不添加注解@Test用不了

    <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>

    1.创建一个Bean 也就是创建名为“User”的类 User.java

    package com.example.demo.entity; import lombok.Data; import java.io.Serializable; @Data public class User implements Serializable { private int id; private String name; }

    2.编写User的配置类 UserConfig.java,在这里实例化一个对象 代码的解释: @Configuration:用于标注配置类,让Spring来加载该类配置作为Bean的载体。在运行时,将为这些Bean生成BeanDefinition和服务请求。 @Bean:产生一个Bean,并交给Spring管理。目的是封装用户、数据库中的数据,一般有Setter、Getter方法。

    package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.demo.entity.User; @Configuration//用于标注配置类 public class UserConfig { //将次返回的值生成一个Bean @Bean("user1")//产生一个Bean,并交给Spring管理 public User user(){ User user=new User(); user.setId(1); user.setName("lishizheng"); return user; } }

    3.编写测试类 实例化一个User对象,然后获取Bean对象user1,该代码位于test文件夹之下

    刚入门的时候这里踩坑:IDEA中cannot resolve method getBean in applicationContext的解决方法

    代码解释 @SpringBootTest:Spring Boot用于测试的注解,可指定入口类或测试环境等。 @RunWith():让测试运行于Spring测试环境 @Test:一个测试方法 ApplicationContext:获取Spring容器中已初始化的Bean,这里是user1

    package com.example.demo.config; import com.example.demo.entity.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class IoCTest { @Autowired private ApplicationContext applicationContext; @Test public void testIoC(){ //实例化User对象,通过上下文获取Bean对象user1 User user=(User)applicationContext.getBean("user1"); //在控制台中打印User数据 System.out.println(user); } }
    Processed: 0.015, SQL: 9