基于注解的IOC配置

xml配置

需要首先扫描包。

<!-- 添加命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描包 -->
    <context:component-scan base-package="xyz.aiinirii"/>

注解格式

  • @Component(是以下三种注解的父类):
    • 作用:把当前类对象存入IOC中
    • 属性:
      • value:用于指定bean的ID,默认值是当前类名首字母小写。
  • @Controller:表现层
  • @Service:业务层
  • @Repository:持久层

以上四种注释方式仅仅名字不同,这样区分可以让我们的三层对象更加清晰。


注解注入

Bean 类型

  • @Autowired:

    • 根据类型注入,只要容器中有唯一一个bean对象的类型和要注入的变量类型匹配,就注入成功。
    • 如果有两个匹配类型,那么就按照变量名称来筛选bean id(选那个和bean id一样的)。
  • @Qualifier:

    • 不能独立使用

      @Autowired
      @Qualifier("BeanId")
      private BeanClass beanName = null;
      
  • @Source:

    • 独立使用

      @Resource("BeanId")
      private BeanClass beanName = null;
      

基本类型和String类型

  • @Value:
    • 属性:
      • value:用SpEL(spring的EL表达式)方式写 - ${param}

集合类型

只能用xml实现


其他注解

  • 作用范围 - @Scope - 同上次笔记中的scope
  • 初始化 - @PostConstruct - 初始化对象
  • 销毁 - @PreDestory - 销毁对象

配置文件(@Configuration)

@Configuration
@ComponentScan("PackageName")
public class Configuration {
    
    @Bean(name = "BeanId")
    public BeanClass createBeanMethod(ParamClass param){
        return beanObject;
    }
    
    @Bean(name = "param")
    publi ParamClass createParamMethod() {
        return paramObject;
    }
}

此时构造ApplicationContext时需要选择:

ApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationClass);

导入其他配置类(@Import)

@Configuration
@ComponentScan("PackageName")
@Import(AnotherConfigurationClass)
public class Configuration {
    
    @Bean(name = "BeanId")
    public BeanClass createBeanMethod(ParamClass param){
        return beanObject;
    }
    
    @Bean(name = "param")
    publi ParamClass createParamMethod() {
        return paramObject;
    }
}

导入PropertySource(@PropertySource)

@Configuration
@ComponentScan("PackageName")
@PropertySource("classpath:PropertyFilePath")
public class Configuration {
    
    @Value("${PropertyId}")
    private ParamType param;
    
    @Bean(name = "BeanId")
    public BeanClass createBeanMethod(ParamClass param){
        return beanObject;
    }
    
    @Bean(name = "param")
    publi ParamClass createParamMethod() {
        return paramObject;
    }
}

Spring整合Junit的配置

  1. 导入spring整合的Junit坐标

  2. 使用Junit提供的一个注解把原有main方法替换成spring提供的方法。

    @RunWith

  3. 告知spring的运行器,spring和IOC是基于xml或注解?

    @ContextConfiguration

    • locations:指定xml文件的位置,加上classpath关键字,表明在类路径下。

    • classes:指定注解类所在的位置。


课程链接:

https://www.bilibili.com/video/BV1Sb411s7vP?from=search&seid=11893869544331926521