【Spring】spring的容器创建

目录

控制反转IOC

依赖注入DI

创建spring的容器方式:

                  思考:

spring整合Junit4


控制反转IOC

把对象的创建和对象之间的调用过程,交给Spring管理,IOC是容器,是思想。!!!

依赖注入DI

可以通过setter注入,自动装配,或者注解的形式,可以看我这个篇文章=>Spring的Bean你了解吗-CSDN博客

创建spring的容器方式:

第一种配置文件

  ApplicationContext  application=new ClassPathXmlApplicationContext("applicationContext.xml");

第二种

   AnnotationConfigApplicationContext application=new AnnotationConfigApplicationContext(SpringConfig.class);
        思考:

        也许大家写过ssm的项目,它好像并没有书写过new 一个spring的容器,那它的spring容器是咋来的?

        在web.xml配置: 在web.xml文件中,通常会配置ContextLoaderListener,该监听器负责初始化Spring容器。这是通过在web.xml中添加以下配置来实现的:      

         配置中,contextConfigLocation 参数指定了Spring配置文件的位置,这里配置文件为 applicationContext.xml。  


<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

        在 web.xml 中配置 ContextLoaderListener 时,可以使用 <load-on-startup> 元素指定加载的顺序。

        通常,<load-on-startup> 的值为一个正整数,表示容器启动时的加载顺序,数值越小越早加载。

        如果 <load-on-startup> 没有配置或者配置为负值,默认情况下,容器会在应用程序首次请求到达时加载 ContextLoaderListener

spring整合Junit4

        每次进行单元测试的时候,都需要编写创建工厂,加载配置文件等代码,比较繁琐。Spring提供了整合Junit单元测试的技术,可以简化测试开发。

  • 必须先有Junit单元测试的环境,也就是说已经导入Junit单元测试的jar包。
  • 再导入spring-test的坐标依赖
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.2.RELEASE</version>
      <scope>test</scope>
 </dependency>
  <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
       <scope>test</scope>
  </dependency>

编写类和方法,把该类交给IOC容器进行管理

package com.aqiuo.demo;
@Component
public class User {
    
    public void sayHello(){
        System.out.println("Hello");
    }
    
}

编写测试代码

@RunWith(value = SpringJUnit4ClassRunner.class)          // 运行单元测试
@ContextConfiguration("classpath:applicationContext.xml")// 加载类路径下的配置文件
public class MyTest2 {

    @Autowired
    User user;

    @Test
    public void run(){
        System.out.println(user);
        user.sayHello();;
    }


}

这样就不用测试spring每次都需要编写创建工厂,加载配置文件等代码。

  • 19
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

五敷有你

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

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

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

打赏作者

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

抵扣说明:

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

余额充值