Spring IOC 容器的理解(七)

本文介绍了Spring框架中基于注解的Bean管理,包括创建配置类、配置自动扫描和完全注解开发。此外,还探讨了与JUnit4的整合,强调了其带来的便利,如自动装配bean和简化测试类的创建。这为学习SpringBoot奠定了基础。
摘要由CSDN通过智能技术生成

第四节 基于注解管理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、操作

①加入依赖


<!-- Spring的测试包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.1</version>
</dependency>

②创建测试类

// 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 容器的文章连续更新结束了,后期会更新其他的好文的,希望多多关注撒

评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红糖番薯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值