一、类级别注解,效果相同

  • 通用:@Component(value="name")
  • Controller层:@Controller(value="name")
  • Service层:@Service(value="name")
  • Dao层:@Repository(value="name")

二、属性注入注解

  • 普通属性注入2种方式: 

   1.在属性上注入,底层使用反射给该字段赋值,破坏了封闭原则,但简易明了。

    @value(“xxx”)

    private String name;

   2.在set方法上注入

    @value("xxx")

    public void setName(String name){

      this.name = name;

    }

  • 引用属性注入

  1. @Autowired和@Qualifier搭配使用

    如果容器中接口对应的只有一个实现类,则按照类型注入,不管属性名称叫什么。如果接口对应的实现类有多个,默认首先按照属性名注入,属性名和类名一致。如果想随意指定某个属性名,则需要使用@Qualifier指定要注入的类名。

    @Autowired
    @Qualifier("plan2")

    private Plan plan;

  2.@Resource

    javax中的注解,重点属性:name按名称注入(不写默认)、type按类型注入

三、生命周期方法注解

         初始化:@PostConstruct

         销毁:@PreDestroy

    均来自于jdk自带注解。

四、作用域

         @Scope("prototype") 多例,默认是单例如,一般springmvc采用单例(有全局变量例外),struts2采用多例

 

前提1:

前提2:

   添加扫描

<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.itheima.g_annotation.a_ioc"></context:component-scan>
</beans>