Spring(四)使用注解注入Bean

注解简单介绍

  1. 是代码里面的特殊标记,使用注解完成功能。
  2. 注解写法@ 注解名称(属性名=属性值)。
  3. 注解可以作用在类、方法、属性上面。

使用流程:

  • 在ApplicationContext.xml中开启注解扫描:

      <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
      <!-- 他会默认扫描com.zhiyou100.crm包下及其子包的所有 有@Controller @Service @Repository @resourse
      	这些注解的类,会把这些对象实例化之后放入容器中.	 -->
      <context:component-scan base-package="com.zhiyou100.crm"><!-- base-package 如果多个,用“,”分隔 -->
      	<!-- 告诉主容器不要扫描加有@Controller 这些类,这些bean 是由web容器进行管理的  -->
      	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    
  • 在Spring-MVC中开启注解扫描:

      <!-- 使用Annotation自动注册Bean,只扫描@Controller 
      use-default-filters="true"
       默认扫描指定包下的全部 @Component(@Controller/@Service/@Repository), exclude-filter 指定的不扫描,include-filter指定的扫描, 
       include-filter和exclude-filter 没有指定的仍然扫描,假設一個service被掃描兩次,有可能導致事物失效
       use-default-filters="false"
       include-filter指定的扫描 ,其他沒有指定的不扫描
      -->
      <context:component-scan base-package="com.zhiyou100.crm.controller" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
      	<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    
  • 在类、方法、属性上添加注解即可。

常用注解说明

在类上,写@scope注解来将类的创建方式修改为单实例或是多实例等

Spring注入属性:

  1. 自动注入: @Autowired
  2. 手动注入: @Resource(name="name")

在类上的四个注解如@Service中写value值如@Service(value="userService")的作用是,当不使用自动注入而采用@Resources注入的时候,在@Resource(name="userService"),这样可以将属性与某个类精确的结合起来,而不是由pool分配.

原文地址:https://www.cnblogs.com/esileme/p/7481677.html