可以使用Ctrl + F搜索,也可以右側目錄自行檢索
@SpringBootApplication
包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。
其中@ComponentScan讓Spring Boot掃描到Configuration類並把它加入到程序上下文。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
申明讓Spring Boot自動給程序進行必要的配置,這個配置等同於:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三個配置。
- @ComponentScan
- 組件掃描,可自動發現和裝配一些Bean。
- @Configuration
- 等同於Spring的XML配置文件;允許在 Spring 上下文中注冊額外的 bean 或導入其他配置類。
- @EnableAutoConfiguration
- 自動配置
@RestController
該注解是@Controller和@ResponseBody的合集,表示這是個控制器Bean,並且是將函數的返回值直接填入HTTP響應體中,是REST風格的控制器。
示例:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return"ok";
}
}
@ResponseBody
@ResponseBody:表示該方法的返回結果直接寫入HTTP Response Body中,一般在異步獲取數據時使用,用於構建RESTful的api。
在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@ResponseBody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP Response Body中。
比如異步獲取json數據,加上@ResponseBody后,會直接返回json數據。
該注解一般會配合@RequestMapping一起使用。
示例:
@RequestMapping(“/test”)
@ResponseBody
public String test(){
return ”ok”;
}
@Autowired 和 @Resource
自動導入。@Resource和@Autowired都是做bean的注入時使用,其實@Resource並不是Spring的注解,它的包是javax.annotation.Resource,需要導入,但是Spring支持該注解的注入。
共同點:兩者都可以寫在字段和setter方法上。兩者如果都寫在字段上,那么就不需要再寫setter方法。
不同點:
@Autowired
- Autowired為Spring提供的注解,需要導入包
org.springframework.beans.factory.annotation. - Autowired只按照byType注入。默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它的required屬性為false。如果我們想使用按照名稱(byName)來裝配,可以結合@Qualifier注解一起使用。如下:
示例:
public class TestServiceImpl {
@Autowired
@Qualifier("userDao")
private UserDao userDao;
}
@Resource
@Resource默認按照ByName自動注入,由J2EE提供,需要導入包javax.annotation.Resource。@Resource有兩個重要的屬性:name和type,而Spring將@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。
所以,如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不制定name也不制定type屬性,這時將通過反射機制使用byName自動注入策略。
示例:
@Resource (name= "baseDao" )
private BaseDao baseDao;
@Qualifier
如上文所述,@Autowired是根據類型進行自動裝配的。如果當Spring上下文中存在不止一個UserDao類型的bean時,就會拋出BeanCreationException異常;如果Spring上下文中不存在UserDao類型的bean,也會拋出BeanCreationException異常。我們可以使用@Qualifier配合@Autowired來解決這些問題。如下:
@Autowired
@Qualifier("userServiceImpl")
public IUserService userService;
總結
- @Autowired: 默認按type注入
- @Qualifier("cusInfoService"): 一般作為@Autowired()的修飾用
- @Resource(name="cusInfoService"): 默認按name注入,可以通過name和type屬性進行選擇性注入
@Component,@Repository,@Service, @Controller
把類標識成可用於 @Autowired 注解自動裝配的 bean 的類
- @Component :通用的注解,可標注任意類為 Spring 組件。如果一個 Bean 不知道屬於哪個層,可以使用@Component 注解標注。
- @Repository : 對應持久層即 Dao 層,主要用於數據庫相關操作。
- @Service : 對應服務層,主要涉及一些復雜的邏輯,需要用到 Dao 層。
- @Controller : 對應 Spring MVC 控制層,主要用於接受用戶請求並調用 Service 層返回數據給前端頁面。
@Scope
聲明 Spring Bean 的作用域
四種常見的 Spring Bean 的作用域:
- singleton : 唯一 bean 實例,Spring 中的 bean 默認都是單例的。
- prototype : 每次請求都會創建一個新的 bean 實例。
- request : 每一次 HTTP 請求都會產生一個新的 bean,該 bean 僅在當前 HTTP request 內有效。
- session : 每一次 HTTP 請求都會產生一個新的 bean,該 bean 僅在當前 HTTP session 內有效。
@Bean
用@Bean標注方法等價於XML中配置的bean。也就是說,相當於XML中的<bean></bean>,放在方法的上面,而不是類,意思是產生一個bean,並交給spring管理。
@Value
注入Spring boot application.properties配置的屬性的值。示例代碼:
@Value(value = “#{message}”)
private String message;
@RequestMapping
RequestMapping是一個用來處理請求地址映射的注解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。
該注解有六個屬性:
params:指定request中必須包含某些參數值是,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。
value:指定請求的實際地址,指定的地址可以是URI Template 模式
method:指定請求的method類型, GET、POST、PUT、DELETE等
consumes:指定處理請求的提交內容類型(Content-Type),如application/json,text/html;
produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回
@RequestParam
將請求參數綁定到你控制器的方法參數上(是springmvc中接收普通參數的注解)
語法:@RequestParam(value=”參數名”,required=”true/false”,defaultValue=””)
value:參數名
required:是否包含該參數,默認為true,表示該請求路徑中必須包含該參數,如果不包含就報錯。
defaultValue:默認參數值,如果設置了該值,required=true將失效,自動為false,如果沒有傳該參數,就使用默認值
@PostMapping("/ali-receive")
public void aliReceive(@RequestParam("message") String message) {
ReceiveLog receiveLog = JSON.parseObject(message, ReceiveLog.class);
}
具體例子:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("hello")
public class HelloController2 {
/**
* 接收普通請求參數
* http://localhost:8080/hello/show16?name=linuxsir
* url參數中的name必須要和@RequestParam("name")一致
* @return
*/
@RequestMapping("show16")
public ModelAndView test16(@RequestParam("name")String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通的請求參數:" + name);
return mv;
}
/**
* 接收普通請求參數
* http://localhost:8080/hello/show17
* url中沒有name參數不會報錯、有就顯示出來
* @return
*/
@RequestMapping("show17")
public ModelAndView test17(@RequestParam(value="name",required=false)String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通請求參數:" + name);
return mv;
}
/**
* 接收普通請求參數
* http://localhost:8080/hello/show18?name=998 顯示為998
* http://localhost:8080/hello/show18?name 顯示為hello
* @return
*/
@RequestMapping("show18")
public ModelAndView test18(@RequestParam(value="name",required=true,defaultValue="hello")String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello2");
mv.addObject("msg", "接收普通請求參數:" + name);
return mv;
}
}
結果分別為:




@PathVariable
用於接收請求路徑中占位符的值
@PathVariable("xxx")
通過 @PathVariable 可以將URL中占位符參數{xxx}綁定到處理器類的方法形參中@PathVariable(“xxx“)
@RequestMapping(value=”user/{id}/{name}”)
請求路徑:http://localhost:8080/hello/show5/1/james
具體例子:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("hello")
public class HelloController2 {
/**
*3、占位符映射
* 語法:@RequestMapping(value=”user/{userId}/{userName}”)
* 請求路徑:http://localhost:8080/hello/show5/1/james
* @param ids
* @param names
* @return
*/
@RequestMapping("show5/{id}/{name}")
public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
mv.setViewName("hello2");
return mv;
}
說明:

結果:

JPA相關
1、@Entity:@Table(name=”“):表明這是一個實體類。一般用於jpa這兩個注解一般一塊使用,但是如果表名和實體類名相同的話,@Table可以省略。
2、@MappedSuperClass:用在確定是父類的entity上。父類的屬性子類可以繼承。
3、@NoRepositoryBean:一般用作父類的repository,有這個注解,Spring不會去實例化該repository。
4、@Column:如果字段名與列名相同,則可以省略。
5、@Id:表示該屬性為主鍵。
6、@GeneratedValue(strategy=GenerationType.SEQUENCE,generator= “repair_seq”):表示主鍵生成策略是sequence(可以為Auto、IDENTITY、native等,Auto表示可在多個數據庫間切換),指定sequence的名字是repair_seq。
7、@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name為sequence的名稱,以便使用,sequenceName為數據庫的sequence名稱,兩個名稱可以一致。
8、@Transient:表示該屬性並非一個到數據庫表的字段的映射,ORM框架將忽略該屬性。
如果一個屬性並非數據庫表的字段映射,就務必將其標示為@Transient,否則,ORM框架默認其注解為@Basic。
9、@Basic(fetch=FetchType.LAZY):標記可以指定實體屬性的加載方式。
10、@JsonIgnore:作用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
11、@JoinColumn(name=”loginId”):一對一:本表中指向另一個表的外鍵。一對多:另一個表指向本表的外鍵。
12、@OneToOne、@OneToMany、@ManyToOne:對應hibernate配置文件中的一對一,一對多,多對一。
全局異常處理
@ControllerAdvice:包含@Component。可以被掃描到。統一處理異常。
@ExceptionHandler(Exception.class):用在方法上面表示遇到這個異常就執行以下方法。
