在Spring1.x時代,還沒出現注解,需要大量xml配置文件并在內部編寫大量bean標簽。Java5推出新特性annotation,為spring的更新奠定了基礎。從Spring 2.X開始spring將xml配置中的對象ioc過程轉化成了注解。Spring Boot之所以能夠輕松地實現應用的創建及與其他框架快速集成,最核心的原因就在于它極大地簡化了項目的配置,最大化地實現了“約定大于配置”的原則。但是注解種類之繁多,還能容易引起混淆,這才有了本文《SpringBoot進階教程(六十四)注解大全》。
要想對SpringBoot注解有個更全面更清晰的認識,就需要分個類,分別是Spring注解、Spring Web注解、Spring Boot注解、Spring Scheduling注解和注解集合。大致可以將注解分為5大類,其中前4類是為了便于理解,分別從4個類別中抽取了一些單獨介紹。而最后一個為注解集合,即可能會表含前面4種注解。
在Spring Core注解中,主要討論Spring DI和Spring IOC中使用的Spring核心注釋。眾所周知,Spring DI和Spring IOC是Spring框架的核心概念。所以介紹 org.springframework.beans.factory.annotation 和org.springframework.context.annotation 包中的注解。這兩個包中注解有很多,就抽取其中的15個注解。
Spring Core Annotations:
單單 org.springframework.context.annotation 這個包下面,注解就有這老些,所以很難列出所有注解舉例,只能抽一些常用的。文末會給出其它注解的作用和定義(盡量給全)。
1.1 @Autowired
@Autowired是一種注解,可以對成員變量、方法和構造函數進行標注,來完成自動裝配的工作,@Autowired標注可以放在成員變量上,也可以放在成員變量的set方法上,也可以放在任意方法上表示,自動執行當前方法,如果方法有參數,會在IOC容器中自動尋找同類型參數為其傳值。
這里必須明確:@Autowired是根據類型進行自動裝配的,如果需要按名稱進行裝配,則需要配合@Qualifier使用;
1.1.1 構造器注入
@RestController
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
}
1.1.2 setter方法注入
@RestController
public class UserController {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
1.1.3 field反射注入
@RestController
public class UserController {
@Autowired
private UserService userService;
}
1.2 @Qualifier
上面已經說到@Autowired按類型裝配Spring Bean。如果容器中有多個相同類型的bean,則框架將拋出NoUniqueBeanDefinitionException, 以提示有多個滿足條件的bean進行自動裝配。程序無法正確做出判斷使用哪一個,通過將@Qualifier注解與我們想要使用的特定Spring bean的名稱一起進行裝配,Spring框架就能從多個相同類型并滿足裝配要求的bean中找到我們想要的,
@Component("studentInfo")
public class StudentInfo implements UserInfo {
public String userName() {
return "student";
}
}
@Component("teacherInfo")
public class TeacherInfo implements UserInfo {
public String userName {
return "teacher";
}
}
@Component
public class UserService {
@Autowired
@Qualifier("studentInfo")
private UserInfo userInfo;
//todo
}
1.3 @Bean
@Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。添加的bean的id為方法名。
@Configuration
public class BeanConfig {
@Bean
public Person userInfo() {
return new UserInfo("toutou", 18);
}
}
這個配置就等同于之前在xml里的配置:
<bean id="userInfo" class="com.test.UserInfo">
<property name="age" value="18"/>
<property name="name" value="請叫我頭頭哥 http://toutou.cnblogs.com"/>
</bean>
1.4 @Required
@Required 注釋應用于 bean 屬性的 setter 方法,它表明受影響的 bean 屬性在配置時必須放在 XML 配置文件中,否則容器就會拋出一個 BeanInitializationException 異常。
@Required
void setUserName(String name) {
this.name = name;
}
<bean class="com.test.UserInfo">
<property name="name" value="請叫我頭頭哥 https://www.cnblogs.com/toutou/" />
</bean>
1.5 @Value
@Value將外部的值動態注入到Bean中。"注入外部的值"可以有很多種,它可以注入普通字符串、注入java 系統變量、注入表達式結果、注入其他Bean屬性、將配置文件 *.properties 或 *. yml 李 配置的 屬性 注入、注入文件資源和注入url資源等。
1.6 @DependsOn
Spring容器載入bean順序是不確定的,Spring框架也沒有約定特定載入順序邏輯規范。@DependsOn注解可以定義在類和方法上,比如說A組件要依賴于B組件,那就是B組件需要比A組件先注冊到IOC容器中。
public class FirstBean {
@Autowired
private SecondBean secondBean;
}
public class SecondBean {
public SecondBean() {
System.out.println("SecondBean init");
}
}
@Configuration
public class BeanConfig {
@Bean("firstBean")
@DependsOn(value = {
"secondBean"
})
public FirstBean firstBean() {
return new FirstBean();
}
@Bean("secondBean")
public SecondBean secondBean() {
return new SecondBean();
}
}
1.7 @Lazy
@Lazy注解用于標識bean是否需要延遲加載。Spring IoC容器一般都會在啟動的時候實例化所有單實例bean,如果想要Spring在啟動的時候延遲加載A,即在調用B的時候再去初始化,則可以使用@Lazy注解。
public class FirstBean {
public void test() {
System.out.println("FirstBean Class");
}
}
public class SecondBean {
public void test() {
System.out.println("SecondBean Class");
}
}
@Configuration
public class AppConfig {
@Lazy(value = true)
@Bean
public FirstBean firstBean() {
return new FirstBean();
}
@Bean
public SecondBean secondBean() {
return new SecondBean();
}
}
1.8 @Lookup
@Lookup的注解是一個作用在方法上的注解,被其標注的方法會被重寫,然后根據其返回值的類型,容器調用BeanFactory的getBean()方法來返回一個bean。
1.9 @Primary
@Primary與@Qualifier類似,都是解決@Autowired時容器中有多個相同類型bean的問題,Primary可以理解為默認優先選擇,同時不可以同時設置多個。
@Component("studentInfo")
public class StudentInfo implements UserInfo {
public String userName() {
return "student";
}
}
@Component("teacherInfo")
@Primary
public class TeacherInfo implements UserInfo {
public String userName {
return "teacher";
}
}
@Component
public class UserService {
@Autowired
@Qualifier("studentInfo")
private UserInfo userInfo;
//todo
}
1.10 @Scope
@Scope注解是springIoc容器中的一個作用域,在 Spring IoC 容器中具有以下幾種作用域:基本作用域singleton(單例)(默認作用域)、prototype(多例),Web 作用域(reqeust、session、globalsession),自定義作用域
1.11 @Profile
@profile注解的作用是為了應對多環境開發,比如開發環境使用dev, 生產環境使用prod,就可以使用@Profile注解實現不同的開發環境使用不同的數據源。spring3.2之前 @Profile注解用在類上,spring3.2 之后 @Profile注解用在方法上
1.12 @Import
@Import用于注入指定的類,導入組件id默認是組件的全類名。
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
1.13 @ImportResource
@ImportResource注解用于導入Spring的配置文件,讓配置文件里面的內容生效;(就是以前寫的springmvc.xml、applicationContext.xml)
@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
public class XmlConfiguration {
}
1.14 @PropertySource
@PropertySource注解加載指定的配置文件
@Configuration
@PropertySource("classpath:config.properties")
public class ProperySourceDemo implements InitializingBean {
@Autowired
Environment env;
@Override
public void afterPropertiesSet() throws Exception {
setDatabaseConfig();
}
private void setDatabaseConfig() {
DataSourceConfig config = new DataSourceConfig();
config.setDriver(env.getProperty("jdbc.driver"));
config.setUrl(env.getProperty("jdbc.url"));
config.setUsername(env.getProperty("jdbc.username"));
config.setPassword(env.getProperty("jdbc.password"));
System.out.println(config.toString());
}
}
1.15 @PropertySources
@PropertySources顧名思義就是可以指定多個@PropertySource來導入配置文件。
@PropertySources({
@PropertySource("classpath:config.properties"),
@PropertySource("classpath:db.properties")
})
public class AppConfig {
//todo...
}
2.1 @RequestBody
主要用來接收前端傳遞給后端的json字符串中的數據的。
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/user")
public UserInfo createUser(@Valid @RequestBody UserInfo user) {
return userService.save(user);
}
}
2.2 @RequestMapping
@RequestMapping是一個用來處理請求地址映射的注解,可用于類或方法上。也就是通過它來指定控制器可以處理哪些URL請求。
@Controller
class UserController {
@RequestMapping(value = "/user/index", method = RequestMethod.GET)
String index() {
return "index";
}
}
2.3 @GetMapping
@GetMapping注釋將Http GET請求映射到特定的處理程序方法。 它是一個組合的注釋,@RequestMapping(method = RequestMethod.GET)的快捷方式。
@GetMapping("/users")
public List<user> getAllUser() {
//...
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId)
throws ResourceNotFoundException {
user user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("user not found for this id :: " + userId));
return ResponseEntity.ok().body(user);
}
2.4 @PathVariable
@PathVariable是spring3.0的一個新功能:接收請求路徑中占位符的值
2.5 @PostMapping
@PostMapping注釋將HTTP POST請求映射到特定的處理程序方法。 它是一個組合的注釋,@RequestMapping(method = RequestMethod.POST)的快捷方式。
@PostMapping("/user/add")
public User addUser(@Valid @RequestBody User user) {
return userRepository.save(user);
}
其它擴展: @PutMapping、@DeleteMapping、@PatchMapping(這三種相對用的比較少,一筆帶過。)
2.6 @ControllerAdvice
增強型控制器,對于控制器的全局配置放在同一個位置。可以用于定義@ExceptionHandler、@InitBinder、@ModelAttribute,可處理全局異常處理、全局數據綁定和全局數據預處理。
@ControllerAdvice(basePackages = {"com.toutou.controller"} )
public class GlobalControllerAdvice {
@InitBinder
public void dataBinding(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
}
@ModelAttribute
public void globalAttributes(Model model) {
model.addAttribute("msg", "Hello World!");
}
@ExceptionHandler(FileNotFoundException.class)
public ModelAndView myError(Exception exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", exception);
mav.setViewName("error");
return mav;
}
}
2.7 @ExceptionHandler
@ExceptionHandler統一處理某一類異常,從而能夠減少代碼重復率和復雜度。
2.8 @InitBinder
@InitBinder只在@Controller中注解方法來為這個控制器注冊一個綁定器初始化方法,方法只對本控制器有效。
2.9 @ModelAttribute
@ModelAttribute注解用于將方法的參數或方法的返回值綁定到指定的模型屬性上,并返回給Web視圖。
2.10 @ResponseBody
@ResponseBody將controller里方法返回的對象通過適當的轉換器轉換為Json寫入到response對象的body區.
2.11 @Controller
@Controller用于標記在一個類上,使用它標記的類就是一個SpringMvc Controller對象,分發處理器會掃描使用該注解的類的方法,并檢測該方法是否使用了@RequestMapping注解。
2.12 @RestController
@RestController在Spring中的作用等同于@Controller + @ResponseBody。
2.13 @RequestParam
@RequestParam將請求參數綁定到你控制器的方法參數上(是springmvc中接收普通參數的注解)
2.14 @CrossOrigin
@CrossOrigin支持跨域,可用于Controller上,也可用于方法上。
@CrossOrigin(origins = "http://toutou.com", maxAge = 3600)
@RequestMapping("/index")
String index() {
return "Hello World!";
}
3.1 @SpringBootApplication
@SpringBootApplication是Sprnig Boot項目的核心注解,目的是開啟自動配置。由于@Configuration,@EnableAutoConfiguration和@ComponentScan三個注解一般都是一起使用,于是spring boot提供了一個統一的注解@SpringBootApplication。即:@SpringBootApplication=@Configuration + @EnableAutoConfiguration + @ComponentScan。
@SpringBootApplication // 等于:@Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如上代碼,是不是簡潔了不少。
3.2 @EnableAutoConfiguration
可以根據classpath中的jar依賴,自動注冊bean,一般用于類或接口上,它嘗試根據您添加的jar依賴項自動配置Spring應用程序。自動載入應用程序所需的所有Bean——這依賴于Spring Boot在類路徑中的查找。
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.3 @ConditionalOnClass、@ConditionalOnMissingClass
3.4 @ConditionalOnBean、@ConditionalOnMissingBean
@ConditionalOnBean // 當給定的在bean存在時,則實例化當前Bean
@ConditionalOnMissingBean // 當給定的在bean不存在時,則實例化當前Bean
@ConditionalOnClass // 當給定的類名在類路徑上存在,則實例化當前Bean
@ConditionalOnMissingClass // 當給定的類名在類路徑上不存在,則實例化當前Bean
3.5 @ConditionalOnProperty
@ConditionalOnProperty可以通過配置文件中的屬性值來判定configuration是否被注入。
3.6 @ConditionalOnResource
@ConditionalOnResource是注解在Configuration bean上,在其加載之前對指定資源進行校驗,是否存在,如果不存在,拋出異常;該注解支持傳入多個變量,
3.7 @ConditionalOnWebApplication、@ConditionalOnNotWebApplication
@ConditionalOnWebApplication主要的用處是: 當Spring為web服務時,才使注解的類生效;通常是配置類;@ConditionalOnNotWebApplication不是web應用。
3.8 @Conditional
@Conditional的作用是按照一定的條件進行判斷,滿足條件給容器注冊bean。
回到頂部
4.1 @Scheduled
@Scheduled可以作為一個觸發源添加到一個方法中。
@Scheduled(fixedDelay=1000)
public void doSomething() {
//...
}
4.2 @EnableScheduling
@EnableScheduling 在配置類上使用,開啟計劃任務的支持(類上)。
@Configuration
@EnableScheduling //通過@EnableScheduling注解開啟對計劃任務的支持
public class TaskScheduleConfig {
//...
}
4.3 @Async
@Async標注的方法,稱之為異步方法;這些方法將在執行的時候,將會在獨立的線程中被執行,調用者無需等待它的完成,即可繼續其他的操作。有時候我們會調用一些特殊的任務,任務會比較耗時,重要的是,我們不管他返回的后果。這時候我們就需要用這類的異步任務啦。
4.4 @EnableAsync
@EnableAsync注解啟用了Spring異步方法執行功能
@Schedules
@Schedules作用跟@Scheduled一樣,@Schedules內部包含多個@Scheduled注解,可以表示一個方法可以存在多個調度設置。
@ComponentScan:表示將該類自動發現掃描組件。個人理解相當于,如果掃描到有@Component、@Controller、@Service等這些注解的類,并注冊為Bean,可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,并結合@Autowired注解導入。可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,并結合@Autowired注解導入。如果沒有配置的話,Spring Boot會掃描啟動類所在包下以及子包下的使用了@Service,@Repository等注解的類。
@Repository:使用@Repository注解可以確保DAO或者repositories提供異常轉譯,這個注解修飾的DAO或者repositories類會被ComponetScan發現并配置,同時也不需要為它們提供XML配置項。
@Inject:等價于默認的@Autowired,只是沒有required屬性;
@Component:泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
@JsonBackReference:解決嵌套外鏈問題。
@JsonIgnore:作用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
@ConfigurationProperties:Spring Boot可使用注解的方式將自定義的properties文件映射到實體bean中,比如config.properties文件。
@ConditionalOnSingleCandidate:組合@Conditional注解,當指定的class在容器中只有一個Bean,或者同時有多個但為首選時才開啟配置。
@ConditionalOnCloudPlatform:組合 @Conditional 注解,當指定的云平臺激活時才開啟配置。
@ConditionalOnJndi:組合 @Conditional 注解,當指定的 JNDI 存在時才開啟配置。
@ConditionalOnJava:組合@Conditional 注解,當運行的 Java JVM 在指定的版本范圍時才開啟配置。
@ConditionalOnExpression:組合 @Conditional 注解,當 SpEL 表達式為 true 時才開啟配置。
@WiselyConfiguration: 組合注解可以替代@Configuration和@ComponentScan
@Transcational: 事務處理
@Target (ElementType.TYPE):元注解,用來指定注解修飾類的那個成員 -->指定攔截規則
@Cacheable: 數據緩存
@ActiveProfiles: 用來聲明活動的 profile
@RunWith: 運行器
作者:頭頭哥
原文鏈接:https://www.cnblogs.com/toutou/p/spring_boot_annotations.html
如果覺得本文對你有幫助,可以轉發關注支持一下
adhesive 粘膠劑
fillers 鞋撐、填料
athletic shoes 運動鞋
finishing room machinery 整理機
binding/laces/braids/cords 鑲邊、線帶、鞋帶
footwear inserts 鞋墊、插入件
bottoming room machinery 鞋底機
heels/wedges/toplifts 鞋跟/楔形鞋跟/鞋后跟底
box toes 內包頭層
buckles and ornament 鞋扣和飾件
insoles 內底
casual 休閑鞋
lasting room machinery 繃幫(裝楦)機
chemical additives 化學添加劑
lasts 鞋楦
containers/boxes 包盒
lining material 襯里材料
cutting room machinery 裁斷機
men’s shoes 男鞋
dance/theatrical 跳舞鞋/戲劇鞋
molds 鞋模
dress shoes 精致鞋、時裝鞋
nails/tacks 釘子/鞋釘、平頭釘
exotic leather 進口皮革
non-wovens 非織布、不織布
fabrics 織物
orthopedics 矯形鞋
fashion boot 時尚靴
outdoor/hiking boots 室外/徒步旅行靴
fasteners 緊固件
outsoles 外底
plastic protective shoes 塑料保護鞋
synthetic leather 合成革
rebuilt second hand machinery 二手設備
skateboard 滑板鞋
rubber/plastic footwear 橡塑鞋
grass-sliding shoe 滑草鞋
safety boots & shoes 安全靴和鞋
basketball shoes 籃球鞋
safety toes/safety inserts 安全鞋頭/安全插件
tourist shoes, travel shoes 旅游鞋
sandals 涼鞋
cotton shoes 棉鞋
shanks 弓形墊
racing shoes 跑鞋
shoe care products 護鞋產品
split 部層皮,二層皮
shoe findings 鞋匠全套工具
artificial leather 人造皮革 shoe boards 鞋板
three-in-one factory “三合一”廠房
shippers 拖鞋
dress shoes, fashion shoes 時裝鞋
soling materials 外底材料
last release 脫楦
stamping systems/foils 燙印,燙印箔
heel part 后幫
stitching machinery 縫紉機,針車
skating shoes 滑冰鞋
top lifts 后跟底層
skiing shoes 滑雪鞋
unit soles 成型底,單元底
family-owned firm 家族企業
upper material 鞋幫材料
glue 膠
work/duty/service footwear 工作鞋
sandals 涼鞋
cloth shoes 布鞋
jogging shoes 慢跑鞋
high-heeled shoes 高跟鞋
insole內底
shareholding system 股份制
leather 皮革
migrant labor 打工、流動勞力
toe part, vamp 前幫
order supervisor 跟單
flip-flops 人字拖鞋
sole 大底,鞋底
beach shoes 沙灘鞋
sewing 縫紉,針車
children shoes 童鞋
work shoes 工作鞋
sole-upper linking 網鞋