Spring容器基本使用

spring 容器的两大接口

spring 中的容器主要有BeanFactory和ApplicationContext。这两个都是用来存储并管理Bean的。BeanFactory提供了基础的容器配置功能,而ApplicationContext则提供了一些企业级特性。

container magic

spring 容器图

BeanFactory

最简单的一个实现,org.springframework.beans.factory.xml.XmlBeanFactory

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xHTbCIZe-1590365057017)(spring 容器.assets/image-20200524230257571.png)]

使用示例:

1、新建一个POJO类
public class BMWCar implements Car {
    @Override
    public String getName() {
        return "宝马汽车";
    }
}
2、创建一个配置文件,这里我们使用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="bMWCar" class="cn.szyrm.pojo.BMWCar"></bean>
</beans>
3、使用容器XmlBeanFactory
package cn.szyrm.beanFactory;


import cn.szyrm.pojo.Car;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class XmlBeanFactoryTest {
    public static void main(String[] args) {
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("xmlBeanFactoryTest.xml"));
        Car bMWCar = beanFactory.getBean("bMWCar", Car.class);
        System.out.println(bMWCar.getName());

    }
}

4、测试

运行main方法,然后我们可以发现在控制台有如下输出

23:16:09.728 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 2 bean definitions from class path resource [xmlBeanFactoryTest.xml]
23:16:09.732 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanFactory - Creating shared instance of singleton bean 'bMWCar'
宝马汽车

这里我们简单的演示了下BeanFactory的用法,在实际的生产环境中几乎不会使用BeanFactroy。而是使用其子接口ApplicationContext来做为Spring的容器。通过这个简单的例子和 spring 容器图 一起理解。这段代码的核心原理无非就是:

  • 1、XmlBeanFactory通过读取配置文件xmlBeanFactoryTest.xml
  • 2、通过xml文件中配置类并通过发射将类进行示例化
  • 3、将实例化话后对象存储在某个地方( 可能是map对象中)
  • 4、通过getBean方法从容器中将之前已经实例化好的对象取出
  • 5、调用实例化好的对象

ApplicationContext

我们来看下其中的一个实现类:org.springframework.context.annotation.AnnotationConfigApplicationContext

类图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xSSgRNK1-1590365057018)(spring 容器.assets/image-20200524234113023.png)]

使用示例

1、POJO还是使用上面的BMWCar
2、配置文件,这里采用基于Java的配置方式
import cn.szyrm.pojo.BMWCar;
import cn.szyrm.pojo.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public Car bMwCar(){
        return new BMWCar();
    }
}

3、使用AnnotationConfigApplicationContext 来读取配置类AppConfig
import cn.szyrm.pojo.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationContextTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        Car car =   applicationContext.getBean(Car.class);
        System.out.println(car.getName());

    }
}
4、测试

运行main方法,我们会发现有如下的输出

23:47:16.699 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1786dec2
23:47:16.713 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
23:47:16.820 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
23:47:16.821 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
23:47:16.822 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
23:47:16.823 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
23:47:16.830 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'appConfig'
23:47:16.833 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'bMwCar'
宝马汽车

容器的使用步骤

从上面我们可以看出,使用spring的基本步骤为:

1、配置元数据

配置元数据就是我们如何装配bean。我们在描述如何装配bean的时候,spring非常的灵活,它提供了三种主要的装配机制:

1)、在xml中进行显示的配置

如前面XmlBeanFactory 的示例所示

2)、在java中进行显示的配置

如前面的前面的ApplicationContext 示例

3)、隐式的bean发现和自动装配

spring是通过两个角度来实现自动化装配的:

  • 1、组件扫描:spring会自动的发现应用上下文中所创建的bean.
  • 2、自动装配:spring自动满足bean之间的依赖。
自动装配示例:
  • 新建一个可被发现的bean

    package cn.szyrm.pojo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class BenzCar implements Car {
        @Autowired
        private Engine engine;
        @Override
        public String getName() {
            return  "奔驰汽车" ;
        }
    
        @Override
        public void start() {
            engine.start();
        }
    }
    
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class DCTEngine implements Engine{
        @Override
        public void start() {
            System.out.println("双离合发动机启动");
        }
    }
    

    这里我们注意到,POJO类BenzCarDCTEngine 上添加了一个@Component注解,这个就是告诉spring 当前类应该被当成一个bean来处理。

  • 在配置类上设置包扫描的路径

    @Configuration
    @ComponentScan("cn.szyrm.pojo")
    public class AppConfig {
    
    }
    
  • 初始容器

    /**
     * 测试spring 的组件扫描及自动注入
     */
    public class ComponentScanTest {
        public static void main(String[] args) {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
            Car car =   applicationContext.getBean("benzCar",Car.class);
    
            car.start();
        }
    }
    
  • 测试使用

    Connected to the target VM, address: '127.0.0.1:51781', transport: 'socket'
    08:01:07.281 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1786dec2
    08:01:07.293 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
    08:01:07.341 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [D:\learn\java\spring-source-learn\target\classes\cn\szyrm\pojo\BenzCar.class]
    08:01:07.342 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [D:\learn\java\spring-source-learn\target\classes\cn\szyrm\pojo\DCTEngine.class]
    08:01:07.426 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
    08:01:07.427 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
    08:01:07.428 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
    08:01:07.429 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
    08:01:07.435 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'appConfig'
    08:01:07.439 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'benzCar'
    08:01:07.445 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'DCTEngine'
    08:01:07.446 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'bMwCar'
    双离合发动机启动
    

2、实列化容器

参考上面的示例

3、使用容器

参考上面的示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值