天天看點

Spring學習(五)——使用注解開發注解說明xml與注解

使用注解開發

  • 注解說明
    • bean注入
    • 屬性注入
    • 自動裝配
    • 作用域
  • xml與注解

spring4之後要使用注解開發就必須保證AOP的包導入

Spring學習(五)——使用注解開發注解說明xml與注解

使用注解需要導入context限制,增加注解的支援

<?xml version="1.0" encoding="UTF-8"?>
<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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

       <!--指定要掃描的包,這個包下面的注解就會生效-->
       <context:component-scan base-package="com.my.pojo"/>
       <context:annotation-config/>



</beans>

           

注解說明

  • bean注入

  • @Component:元件,放在類上,說明這個類被Spring管理了,就是bean!
    Spring學習(五)——使用注解開發注解說明xml與注解
    Component在不同的包下的注解可以不一樣,但是意義一樣都是将類裝配到Spring的容器中
    Spring學習(五)——使用注解開發注解說明xml與注解

屬性注入

@Value()

Spring學習(五)——使用注解開發注解說明xml與注解

自動裝配

  • @Autowired:自動裝配通過類型。名字如果Autowired不能唯一自動裝配上屬性,則需要通過@Qualifier(value=“xxx”)
  • @Nullable字段标記了這個注解,說明這個字段可以為null;
  • @Resource :自動裝配通過名字。類型。

作用域

@Scope()

Spring學習(五)——使用注解開發注解說明xml與注解

xml與注解

xml更加萬能,适用于任何場合,維護簡單友善

注解如果不是自己的類,不在同一個類下就無法使用,維護相對複雜

開啟注解第一要有context限制,第二是要掃描到要添加注解的包下