spring IoC注解

三、spring之IOC注解

多spring配置文件的使用(分模块开发,每个模块可能有自己的spring配置文件)

spring IoC注解_第1张图片
spring IoC注解_第2张图片

(一)、搭建使用注解的方式 ioc注解

1. 有xml配置文件(xml配置+注解组合使用)

第一步、要使用注解,需导入aop包
第二步、在配置文件头部加入context的schema
spring IoC注解_第3张图片

使用配置文件使用
组件扫描,扫描里边有标注@Component, @Repository, @Service, @Controller的类变成组件,把这些类注册到spring ioc容器中,等价于在配置文件中使用

<bean id="" class="">
<context:component-scan base-package="org.lanqiao.entity">context:component-scan>

把entity包下的有注解的类注册到spring ioc容器中

第三步、使用注解
@Component 注解
@Repository, 专门注解到dao层
@Service, 专门注解到service层
@Controller 专门注解到controller层

@Lazy懒加载
@Scope(“singleton”)
@Scope(“prototype”)

2. 零配置(没有xml文件,全部用配置类)

(1)使用@Bean进行注册(缺点:每一个类都要手动编写注册)
spring IoC注解_第4张图片

(2)不使用@Bean注解(缺点:)

spring IoC注解_第5张图片
spring IoC注解_第6张图片

(二)、使用其他注解 DI依赖注入注解

1.使用xml的属性注入
spring IoC注解_第7张图片
spring IoC注解_第8张图片
spring IoC注解_第9张图片
spring IoC注解_第10张图片

2.使用注解来完成DI注入
spring IoC注解_第11张图片
spring IoC注解_第12张图片
spring IoC注解_第13张图片
spring IoC注解_第14张图片

@Autowired 等价于byType,按类型进行注入,优先查找类型,类型匹配不成功或有多个,继续按 名称进行查找组合查找注入(优先根据名字)

  • @Autowired

  • @Qualifier(“studentDao2”)//byName

  • @Autowired(required=true) true:必须能注入值进来,默认的,在ioc容器找不到匹配就会抛异常
    false:在ioc容器找不到的时候注入null进来,不会抛异常

  • @Primary 设置主要类,当ioc容器中调用@autowire自动注入时,因按类型匹配注入,当出现多个同一类型的bean时,优先选择设置了@primary的bean,而不会报错

  • @Resource//byName按名称查找 @Resource(name=“studentDao2”)

  • @Value 基本值的注入
    在这里插入图片描述

注解方式导入属性文件:
spring IoC注解_第15张图片

xml方式导入属性文件
在这里插入图片描述

使用@Value进行值的注入
spring IoC注解_第16张图片

@PostConstruct, 注解到方法上
@PreDestroy 注解到方法上

使用注解的地方:
spring注解 java注解 springmvc注解 springboot注解

注解和xml同时使用
使用配置类作为主导文件
spring IoC注解_第17张图片
在这里插入图片描述

使用xml文件作为主导配置文件
spring IoC注解_第18张图片

总结:IOC和DI相比传统的方式如何实现解耦的

你可能感兴趣的:(spring,ioc)