# 注解實現自動裝配 ###### tags: `Spring-bean的自動裝配` jdk1.5支持的注解,Spring2.5開始支持注解 ### 要使用注解須知: 1.導入約束。context約束 2.配置注解的支持 <context:annotation-config/> **【重要】** ```xml= <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans> ``` ### 注解種類 1.@Autowired 直接在屬性上使用即可,也可以在set方式上使用 使用Autowired我們可以不用編寫set方法,前提是你這個自動裝配的屬性在IOC(Spring)容器中存在,且符合名字byName ```java= public class People { @Autowired private Cat cat; @Autowired public Dog dog; private String name; } ``` 使用後,能在People類的引用屬性中看到提示   科普: ```java= //字段標記了這個注解,說明這個字段可以為null @Nullable ``` ```java= public People(@Nullable String name) { this.name = name; } ``` Autowired默認為true ```java= public @interface Autowired { boolean required() default true; } ``` 如果顯式定義了Autowired屬性為false,說明這個對象可以為null,否則不允許為空 ```java= @Autowired(required = false) private Cat cat; ``` 如果@Autowired自動裝配的環境比較複雜,自動裝配無法通過一個注解【@Autowired】完成的時候,我們可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一個唯一的bean對象注入 ```xml= <bean id="dog11" class="com.kuang.pojo.Dog"/> <bean id="dog21" class="com.kuang.pojo.Dog"/> ``` ```java= public class People { @Autowired(required = false) private Cat cat; @Autowired @Qualifier(value = "dog11") public Dog dog; private String name; } ``` 2.@Resource java的原生注解,會先在bean.xml用名字去查找,查找不到再找類,如果是唯一類就能使用 ```java= public class People { @Resource private Cat cat; } ``` 如果名字不符,類型也不唯一,則可以透過@Resource(name = "")來指定 ```xml= <bean id="cat1" class="com.kuang.pojo.Cat"/> <bean id="cat2" class="com.kuang.pojo.Cat"/> ``` ```java= public class People { @Resource(name = "cat1") private Cat cat; } ``` ### 小結: @Resource和@Autowired的區別: * 都是用來自動裝配,都可以放在屬性字段上 * @Autowired透過byType的方式實現,而且必須要求這個對象存在【常用】 * @Resource默認透過byname的方式實現,如果找不到名字,則透過byType實現,如果兩個都找不到的情況,報錯 * 執行順序不同: @Autowired透過byType @Resource默認透過byname
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up