Spring IOC 容器的理解(七)

第四节 基于注解管理bean

第一个实验 [重要]标记与扫描

第二个实验 [重要]自动装配

第三个实验 完全注解开发

第四个实验 整合junit4

第三个实验 完全注解开发

1、使用配置类取代配置文件

①创建配置类

②根据配置类创建IOC容器对象

2、在配置类中配置bean

3、在配置类中配置自动扫描的包

第三个实验 完全注解开发

体验完全注解开发,是为了给将来学习SpringBoot打基础。因为在SpringBoot中,就是完全舍弃XML配置文件,全面使用注解来完成主要的配置。

1、使用配置类取代配置文件

①创建配置类

使用@Configuration注解将一个普通的类标记为Spring的配置类。

package com.atguigu.ioc.configuration;
    
import org.springframework.context.annotation.Configuration;
    
@Configuration
public class MyConfiguration {
}

②根据配置类创建IOC容器对象

// ClassPathXmlApplicationContext根据XML配置文件创建IOC容器对象
private ApplicationContext iocContainer = new ClassPathXmlApplicationContext("applicationContext.xml");
​
// AnnotationConfigApplicationContext根据配置类创建IOC容器对象
private ApplicationContext iocContainerAnnotation = new AnnotationConfigApplicationContext(MyConfiguration.class); 

2、在配置类中配置bean

使用@Bean注解

@Configuration
public class MyConfiguration {
    
    // @Bean注解相当于XML配置文件中的bean标签
    // @Bean注解标记的方法的返回值会被放入IOC容器
    @Bean
    public CommonComponent getComponent() {
    
        CommonComponent commonComponent = new CommonComponent();
    
        commonComponent.setComponentName("created by annotation config");
    
        return commonComponent;
    }
    
}

3、在配置类中配置自动扫描的包

@Configuration
@ComponentScan("com.atguigu.ioc.component")
public class MyConfiguration {
    ……

第四个实验 整合junit4

1、整合的好处

2、操作

①加入依赖

②创建测试类

第四个实验 整合junit4

1、整合的好处

  • 好处1:不需要自己创建IOC容器对象了
  • 好处2:任何需要的bean都可以在测试类中直接享受自动装配

    2、操作

    ①加入依赖

     org.springframework spring-test 5.3.1

    ②创建测试类

    // junit的@RunWith注解:指定Spring为Junit提供的运行器
    @RunWith(SpringJUnit4ClassRunner.class)
    ​
    // Spring的@ContextConfiguration指定Spring配置文件的位置
    @ContextConfiguration(value = {"classpath:applicationContext.xml"})
    public class JunitIntegrationSpring {
        
        @Autowired
        private SoldierController soldierController;
        
        @Test
        public void testIntegration() {
            System.out.println("soldierController = " + soldierController);
        }
        
    } 

    其实在javaservlet中规定servlet必须在容器中管理,而spring框架更是很好的提供了我们这个环境,在最初的spring框架中采用xml和bean对ioc容器进行管理,在springboot以及后续升级框架中管理方式以及装配方式会有所改变,但是原理都是有spring框架基础的演变过来的,只要掌握了spring框架的基本原理,在后续的学习当中我们会更容易的去使用并且理解其他衍生框架的含义,例如springmvc以及springboot和springcloud等衍生框架,更加方便了我们对框架的理解与学习。

    关于IOC 容器的文章连续更新结束了,后期会更新其他的好文的,希望多多关注撒