# 使用注解開發(注解總結) ###### tags: `Spring-bean的自動裝配` 在Spring4之後,要使用注解開發,必須要保證aop的包導入 ![](https://i.imgur.com/9K096Zw.png) 在使用注解需要導入context約束,增加注解的支持! ```xml= <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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/context/spring-aop.xsd"> <context:annotation-config/> </beans> ``` ### 1.bean #### 注解說明: 1.@Component:組件,放在類上,說明這個類被Spring管理,就是bean 不需要在applicationContext.xml編寫這個類的bean ```java= //等價於<bean id = "user" class="com.kuang.pojo.User"/> //@Component 組件 @Component public class User { public String name = "秦心"; } ``` ### 2.屬性如何注入 @Value ```java= public class User { //相當於<property name = "name" value = "戀戀"/> @Value("戀戀") public String name; } ``` 也可以在set方法注解 ```java= //相當於<property name = "name" value = "戀戀"/> @Value("戀戀") public void setName(String name) { this.name = name; } ``` ### 3.衍生的注解 @Component有幾個衍生注解,我們在web開發中,會按照mvc三層架構分層! * dao 【@Repository】 * service 【@Service】 * controller 【@Controller】 這四個注解功能都是一樣,都是代表將某個類註冊到Spring容器中,裝配Bean ### 4.自動裝配 * @Autowired透過byType的方式實現,而且必須要求這個對象存在【常用】 * @Resource默認透過byname的方式實現,如果找不到名字,則透過byType實現,如果兩個都找不到的情況,報錯 * @Nullable:字段標示了這個注解,說明這個字段可以為null ### 5.作用域 @Scope() ```java= @Component @Scope("singleton") public class User { public String name; //相當於<property name = "name" value = "戀戀"/> @Value("戀戀") public void setName(String name) { this.name = name; } } ``` ### 6.小節 xml與注解的差別 * xml更加萬能,適用於任何場合,維護簡單方便 * 注解,不是自己的類使用不了,維護相對複雜 xml與注解的最佳實踐 * xml用來管理bean * 注解只負責完成屬性注入 * 我們在使用的過程中,只需要注意一個問題:必須讓注解生效,就需要開啟注解的支持 ```xml= <!--指定要掃描的包,這個包下的注解就會生效--> <context:component-scan base-package="com.kuang"/> <context:annotation-config/> ```