Spring的核心Spring-core

1.通过Maven获取Spring-core的架包以及依赖包

  • 在pom.xml文件中。
<!-- Spring依赖1:spring-core -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>5.2.1.RELEASE</version>
</dependency>
<!-- Spring依赖2:spring-beans -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>5.2.1.RELEASE</version>
</dependency>
<!-- Spring依赖3:spring-context -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.1.RELEASE</version>
</dependency>

注意:Spring的三个依赖必须使用相同版本

2.Spring-core概念:

Spring-cord相当于一个创建并管理bean的容器:

  • 创建:底使用反射技术创建bean的实例
  • 管理:容器中的每个bean,spring容器默认按照单例模式管理。
  • 设计:使用工厂设计模式(BeanFactory)
<!--默认采用单例的方式管理Bean 默认状态下,获取该bean多次为同一个对象-->
<!--单例模式:scope默认为:singleton  只会创建一个对象  prototype 会创建多个对象-->
<!--init-method属性:用于声明初始化方法-->
<!--destroy-method属性:用于声明销毁方法-->
<bean id="messageServiceBean"
      class="com.apesource.service.impl.MessageServiceImpl"
      scope="prototype" 
      init-method="init" 
      destroy-method="destroy"/>

两种获取Spring容器的方式:

  • ClassPathXmlApplicationContext:在classpath路径下加载xml配置文件,完成Spring容器的加载;或者采用注解方式时,需要在xml配置文件中使用<context:component-scan />完成类扫描。
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config2.xml");
    
  • AnnotationConfigApplicationContext:基于注解配置的Spring容器加载方式。
    ApplicationContext context = new AnnotationConfigApplicationContext("com.apesource");
    

3.IOC(Inverse Of Control)与DI(Dependency Injection)

IOC和DI分别指的是控制反转和依赖注入,将项目中的类(组件)交给Spring容器管理,按照组件之间彼此的依赖关系(采用xml配置文件或者注解或者Javaconfig),完成组件之间的注入,降低组件之间的耦合。
三种注入方式:

  • 属性setter注入
     <!--1.属性注入-->
    <property name="messageService" ref="messageServiceBean"/>
    
  • 构造注入(使用有参构造方法进行注入)
    <!--2.构造方法注入-->
    <constructor-arg name="messageService" ref="messageServiceBean"/>
    <constructor-arg name="defaultMsg" value="默认消息模板"/>
    
  • 接口注入

三种配置方式

  • 使用XML配置:优势:配置内容直观清晰、扩展灵活。劣势:配置繁琐。
  • 使用注解配置:优势:简洁。劣势:扩展不灵活。
  • 使用JavaConfig配置:优势:借助IDE工具,确保配置内容准确。劣势:配置代码比较多,扩展不灵活。

4.Spring-core的注解

  • 声明bean
    • @Component:组件
    • @Controller:控制器组件
    • @Service:业务层组件
    • @Repository:数据访问层组件
  • 声明注入
    • 使用Spring Framework的注解
      • @Autowired:自动装配(默认按照类型自动装配),按照当前声明的接口类型,在容器中查找该接口实现类对象bean,进行自动注入(装配)。
      • @Qualifier:按照bean名称自动装配,与@Autowired注解配合使用。按照当前指定的bean名称,在容器中查找该名称对应的bean,进行自动注入(装配)。
    • 使用Java标准注解
      • @Resource:javax扩展包提供的注解,完成自动注入,默认按照类型自动注入,也可使用name属性进行按名称自动注入。
  • 其他
    • @Primary:当前bean,当发现多个相同类型的bean,以主要bean为首选。
    • @Scope("prototype"):设置bean的作用域为每次获取时创建新的bean;默认为单例。
    • @Configuration:设置当前类为配置文件类。(JavaConfig配置中使用)
    • @Bean:设置当前方法为bean的创建方法、方法名即为bean的名称。(JavaConfig配置中使用)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。