配置注解的支持:
在spring4之后,想要使用注解形式,必須得要引入 aop 的包
1
2
3
4
5
|
< dependency > < groupId >org.springframework</ groupId > < artifactId >spring-aop</ artifactId > < version >5.2.8.RELEASE</ version > </ dependency > |
導入 context 的約束,增加注解的支持:
1
2
3
4
5
6
7
8
9
10
11
|
<? 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 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:annotation-config /> </ beans > |
配置掃描指定包下的注解
<!--指定注解掃描包-->
<context:component-scan base-package="com.lf.pojo"/>
常用注解說明
自動裝配注解
-
@Autowired:自動裝配,其作用是為了消除Java代碼中的getter/setter方法和bean中的property屬性。其中是否消除getter程序需求,若需要對外提供私有屬性,則應當保留
- @Autowired是按類型自動轉配的,不支持id匹配
- 需要導入 spring-aop 包
- 如果@Autowired不能唯一自動裝配上屬性則需要通過 @Resource(value="xxx")
-
@Quali?er :如果容器中有一個以上匹配的Bean,則可以通過@Qualifier注解限定Bean的名稱
- @Autowired是根據類型byType自動裝配的,若加上@Quali?er則可以根據byName的方式自動裝配
- @Quali?er不能單獨使用
- @Resource:自動裝配,通過名字,類型。與@Autowired注解作用非常相似
-
@Autowired與@Resource異同總結:
- @Autowired與@Resource都可以用來裝配bean。都可以寫在字段上,或寫在setter方法上
- @Autowired默認按類型裝配(屬于spring規范),默認情況下要求依賴對象必須存在,若要允許null 值,則可以設置它的required屬性為false,如:@Autowired(required=false) ,如果想使用名稱裝配可以結合@Quali?er注解使用
- @Resource默認按照名稱裝配,名稱可以通過name屬性進行指定。若未指定name屬性,當注解位于字段上時,會默認按字段名通過名稱查找;若注解寫在 setter方法上則默認取屬性名進行裝配。 當找不到與名稱匹配的bean時才按照類型進行裝配。但需要注意的是:name屬性一旦指定,就只會按照名稱進行裝配
- 它們的作用相同都是用注解方式注入對象,但執行順序不同。@Autowired 先 byType,@Resource 先 byName
Bean的實現
@Component:它的作用就是實現bean的注入,@Component 注解可以放在類的上面,但@Component不推薦使用
Spring提供了更加細化的注解形式:@Repository、@Service、@Controller,它們分別對應存儲層Bean,業務層 Bean,和展示層Bean。因此推薦使用它們來替代@Component
屬性注入
使用注解注入屬性
可以不用提供set方法,直接在直接名上添加@value("值")
@Component("user")
// 相當于配置文件中
public class User {
@Value("Java")
// 相當于配置文件中
public String name;
}
```
如果提供了set方法,在set方法上添加@value("值")
1
2
3
4
5
6
7
8
|
@Component ( "user" ) public class User { public String name; @Value ( "Java" ) public void setName(String name) { this .name = name; } } |
衍生注解
@Component的三個衍生注解
為了更好的進行分層,Spring可以使用其它三個注解,其功能一樣,都是代表將某個類注冊到spring中,裝配Bean
@Controller:web層
@Service:service層
@Repository:dao層
作用域
@scope
- singleton:默認的,Spring會采用單例模式創建這個對象。關閉工廠 ,所有的對象都會銷毀
- prototype:多例模式。關閉工廠 ,所有的對象不會銷毀。內部的垃圾回收機制會回收
@Controller("user") @Scope("prototype") public class User { @Value("秦疆") public String name; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/lf-637/p/13388272.html