注解簡單介紹
- 是代碼里面的特殊標記,使用注解完成功能。
- 注解寫法@ 注解名稱(屬性名=屬性值)。
- 注解可以作用在類、方法、屬性上面。
使用流程:
-
在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注入屬性:
- 自動注入: @Autowired
- 手動注入: @Resource(name="name")
在類上的四個注解如@Service中寫value值如@Service(value="userService")的作用是,當不使用自動注入而采用@Resources注入的時候,在@Resource(name="userService"),這樣可以將屬性與某個類精確的結合起來,而不是由pool分配.