Spring注解大全

1.@Controller

1.作用

组合注解(组合了@Component注解),应用在MVC层(控制层),DispatcherServlet会自动扫描注解了此注解的类,然后将web请求映射到注解了@RequestMapping的方法上。

2.@Service

1.作用

组合注解(组合了@Component注解),应用在service层(业务逻辑层)

3.@Reponsitory

1.作用

组合注解(组合了@Component注解),应用在dao层(实现类)(数据访问层)

4.@component

1.作用

把类实例化到spring容器中,交给Spring管理,相当于配置文件中的

当不知道这个类是属于业务,控制,还是dao层时,所以就用@Component

5.@Autowired

1.作用

依赖注入,给对象的属性注入数据,可以定义在字段上,也可以定义在方法上。一般用在注入dao层数据源

6.@Resource

1.作用

依赖注入,给对象的属性注入数据,可以定义在字段上,也可以定义在方法上。一般用在注入dao层数据源,跟@Autowired相似,区别就是@Autowired默认是先根据类型,而@Resource默认是先根据名称

2.语法

1.@Resource注解注解的name属性不为空

1)首先创建Person类,并纳入容器中管理:

/*纳入容器中后,bean的id名字为ps(也就是容器中id名为ps)*/
@Component(value="ps")
public class Person {

    public void say(){
        System.out.println("------say()------");
    }
}
@Component
public class Man {

    /**从容器中取id名字为ps的bean,如果找不到该bean,
      *spring启动过程中就会报错,表示把Man类型的bean注入到容器中不成功,
      *因为person的属性依赖注入的时候就出错了,所以创建Man的bean的时候肯定不成功。
    **/
    @Resource(name="ps")
    private Person person;

    /**依赖注入失败,因为Person类型注入到容器中的bean的id指定为ps,
      *所以从容器中获取id为person的bean就会失败
     **/
    //  @Resource(name="person")
    //  private Person ps;

    public void work(){
        person.say();
        System.out.println("------work()------");
    }
}

PS:注入dao层时,name的名称可以自定义,因为dao接口已经用注解形式创建对象了,所以在bean里面没有配置名称。

2.@Resource注解注解的name属性为空

1)@Resource要注解的那个变量属性与容器中的bean的id的名字相等
启动类和Person的类与相面一样,下面直接修改Man类如下:

@Component
public class Man {

    /*@Resource注解的属性变量ps与容器中的bean的id名字ps相等,可以匹配*/
    @Resource
    private Person ps;

    public void work(){
        ps.say();
        System.out.println("------work()------");
    }
}

2)@Resource要注解的那个变量属性与容器中的bean的id的名字不相等

这种如果有变量类型与容器中的类型相等的话,也不会报错,只有两个不符合才报错

@Component
public class Man {

    /**@Resource注解的属性变量ps与容器中的bean的id名字ps不相等,
      *然后通过bean的类型判断:person变量属性的类型为Person类,
      *容器中的id为ps的bean的类型也为Person类型,因此此种情况下也可以匹配
     **/
    @Resource
    private Person person;

    public void work(){
        person.say();
        System.out.println("------work()------");
    }
}

7.@RequestParam

1.作用
@RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)
2.语法
语法1@RequestParam(value=”参数名”,required=true/false,defaultValue=””)
 
value:参数名
 
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
 
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,
就使用默认值

语法2@RequestParam("参数名")
3.示列

@Controller
@RequestMapping("/bdCheliang")
public class HelloController {
 
    /**
	 * 接收普通请求参数
	 * http://localhost:8080/bdCheliang/show1?name=liu
	 * url参数中的name必须要和@RequestParam("name")一致,
	 * 因为请求参数绑定到你控制器的方法参数,所以方法参数可以自定义
	 * 
	 */
	@RequestMapping("/show1")
	@ResponseBody
	public String test1(@RequestParam("name")String name1){
		System.out.println(name1);
		return name1;

	}
 
    /**
	 * 接收普通请求参数
	 * http://localhost:8080/bdCheliang/show2?name=lin
	 * url参数中的name必须要和@RequestParam("name")一致
	 * url中没有name参数不会报错、有就显示出来
	 * @return
	 */
	@RequestMapping("/show2")
	@ResponseBody
	public String test2(@RequestParam(value="name",required=false)String name2){
		System.out.println(name2);
		return name2;

	}
 
  /**
	 * 接收普通请求参数
	 * http://localhost:8080/bdCheliang/show3?name=998 显示为998
	 * http://localhost:8080/bdCheliang/show3?name 显示为hello
	 * @return
	 */
	@RequestMapping("/show3")
	@ResponseBody
	public String test3(@RequestParam(value="name",required=true,defaultValue="hello")String name3){
		System.out.println(name3);
		return name3;

	}
 
}

8.@RequestBody

1.作用

主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)

GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。

在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。

注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。

2.语法
@RequestBody 参数类型 参数
3.使用时机

GET、POST方式提交时, 根据 request header Content-Type 的值来判断:

  • application/x-www-form-urlencoded可选(即非必须,因为这种情况的数据 @RequestParam, @ModelAttribute 也可以处理,当然@RequestBody也能处理);
  • multipart/form-data:**不能处理(**即使用@RequestBody不能处理这种格式的数据);
  • 其他格式:必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

PUT 方式提交时, 根据request header Content-Type的值来判断:

  • application/x-www-form-urlencoded必须
  • multipart/form-data不能处理
  • 其他格式:必须
4.示列

1.@RequestBody直接以String接收前端传过来的json数据

/***
	  * 直接以String接收前端传过来的json数据
	  * 
	  * @Param str:json格式的字符串
	  * @return: json格式的字符串
 **/
@PostMapping("/test")
@ResponseBody
public String test(@RequestBody String str){

		return str;
}

使用PostMan测试:

在这里插入图片描述

2.@RequestBody以简单对象接收前端传过来的json数据

  /***
	 * 以User对象接收前端传过来的json数据
	 *
	 * @Param user:用户实体类
	 * @return: user重写后的toString
	 **/
	@PostMapping("/test2")
	@ResponseBody
	public String test2(@RequestBody User user){
		System.out.println(user.getName());
		System.out.println(user.getAge());

		return user.toString();
	}

使用PostMan测试:

在这里插入图片描述

3.@RequestBody与简单的@RequestParam()同时使用

/***
	 * @RequestBody与@RequestParam()同时使用
	 *
	 * @Param user:用户实体类
	 **/
	@PostMapping("/test3")
	@ResponseBody
	public String test3(@RequestBody User user,@RequestParam("token") String tk){
		System.out.println(user.getName());
		System.out.println(user.getAge());
		System.out.println(tk);

		return tk + "----" + user.toString();
	}

使用PostMan测试:

在这里插入图片描述

4.不加@RequestParam()注解接收URL中的数据并组装为对象

@PostMapping("/test3")
	@ResponseBody
	public String test3(User user){
		System.out.println(user.getName());
		System.out.println(user.getAge());


		return user.toString();
	}

使用PostMan测试:

在这里插入图片描述

9.@RestController

1.作用

组合注解,@RestController注解相当于@ResponseBody + @Controller合在一起的作用

1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

例如:本来应该到success.jsp页面的,则其显示success.

2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。

3)如果注解是@controller的情况,需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

10.@ResponseBody

1.作用

1)将java对象转为json格式的数据

2)在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。

2.使用时机

返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如 json、xml 等)使用。

3.示列
@PostMapping("/test3")
@ResponseBody
public String test3(User user){
		System.out.println(user.getName());
		System.out.println(user.getAge());
    // 没有加@ResponseBody会跳转到success的路径
    //加上@ResponseBody注解后不会被解析为跳转路径,而是直接写入 HTTP 响应正文中,转化为json格式
		return "success";  
	}

11.@RequestMapping

1.作用

用来处理请求地址映射的注解,可用于类或方法上;用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

2.语法

RequestMapping注解有六个属性

1.value, method属性

value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method: 指定请求的method类型, GET、POST、PUT、DELETE等;

@RequestMapping(value="/test", method=RequestMethod.GET)

2.consumes,produces

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

@RequestMapping(value = "/test", method = RequestMethod.GET, consumes="application/json",produces="application/json")

3、 params,headers

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

params的样例:

// 仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
@RequestMapping(value = "/test", method = RequestMethod.GET, params="myParam=myValue")

headers的样例:

// 仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.baidu.com/”的请求;
@RequestMapping(value = "/test", method = RequestMethod.GET, headers="Referer=http://https://www.baidu.com//")
3.示列

1.value 、method 示例

@RequestMapping(value="/test1", method=RequestMethod.GET)
@ResponseBody
public String test1(User user) {
  return "ok"; 
}

2.consumes、produces 示例

// 方法仅处理request Content-Type为“application/json”类型的请求。
@RequestMapping(value="/test1", method=RequestMethod.GET,consumes="application/json")
@ResponseBody
public String test1(User user) {
  return "ok"; 
}

// 方法仅处理request请求中Accept头中包含了"application/json"的请求
// 同时返回的内容类型为application/json;
@RequestMapping(value="/test2", method=RequestMethod.GET,produces="application/json")
@ResponseBody
public String test1(User user) {
  return "ok"; 
}

3. params、headers 示例

// 仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
@RequestMapping(value="/test1", method=RequestMethod.GET,params="myParam=myValue")
@ResponseBody
public String test1(User user) {
  return "ok"; 
}

// 仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.baidu.com/”的请求;
@RequestMapping(value="/test2", method=RequestMethod.GET, headers="Referer=http://https://www.baidu.com//")
@ResponseBody
public String test1(User user) {
  return "ok"; 
}

12.@PostMapping

组合注解,@postMapping = @requestMapping(method = RequestMethod.POST)。

13.@GetMapping

组合注解,@getMapping = @requestMapping(method = RequestMethod.GET)。

14.@Scope

1.作用

指定bean的作用域,基本作用域singleton(单例)、prototype(多例),Web 作用域(reqeust、session、globalsession),自定义作用域

1.singleton单例模式 – 全局有且仅有一个实例
2.prototype多例 – 每次获取Bean的时候会有一个新的实例
3.request – request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效
4.session – session作用域表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效
5.globalsession – global session作用域类似于标准的HTTP Session作用域,不过它仅仅在基于portlet的web应用中才有意义

2.语法

@Scope("prototype")//多实例,IOC容器启动创建的时候,并不会创建对象放在容器在容器当中,当你需要的时候,需要从容器当中取该对象的时候,就会创建。
@Scope("singleton")//单实例 IOC容器启动的时候就会调用方法创建对象,以后每次获取都是从容器当中拿同一个对象(map当中)。
@Scope("request")//同一个请求创建一个实例
@Scope("session")//同一个session创建一个实例

3.示列

直接在创建bean对象上增加@Scope注解,比如@controller创建bean对象,在此添加@Scope注解即可

@Controller
@RequestMapping("/bdCheliang")
@Scope("prototype")
public class BdCheliangController {
   
    @Autowired
	  private BdCheliangService bdCheliangService;
   
  	@RequestMapping(value="/test", method=RequestMethod.GET)
  	@ResponseBody
	  public String test1(User user) {
		  return "ok";
	  }
}

15.@Value

1.作用

通过注解将常量、配置文件中的值、其他bean的属性值注入到变量中,作为变量的初始值

2.示列

1.常量注入

	@Value("wei")
	private String name;
	@RequestMapping(value="/test1")
	@ResponseBody
	public String test1() {
		return name;
	}

2.将配置文件 .properties 或. yml里配置的属性注入

1)编辑properties配置文件或者yml配置文件
在这里插入图片描述

2)注入变量中

	@Value("${user.username}")
	private String username;
	@RequestMapping(value="/test2")
	@ResponseBody
	public String test2() {
		return username;
	}

3.注入文件资源

@Value("classpath:com/hry/spring/configinject/config.txt")
private Resource resourceFile; // 注入文件资源

4.注入url资源

@Value("http://www.baidu.com")
private Resource testUrl; // 注入URL资源

5.注入表达式结果

  @Value("#{ 10 % 6}")
	private double randomNumber; //注入表达式结果
	@RequestMapping(value="/test3")
	@ResponseBody
	public double test3() {
		return randomNumber;
	}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架中,有很多注解可以用来实现依赖注入和组件扫描等功能。以下是一些常用的Spring注解: 1. @Autowired:用于自动装配依赖关系。默认按照byType方式进行bean匹配,可以通过指定name属性或者使用@Qualifier注解来指定bean的名称。 2. @Resource:与@Autowired注解作用相似,但是默认按照byName方式进行bean匹配。可以通过指定name属性或者type属性来指定bean的名称或类型。 3. @Component:用于标注一个普通的Spring组件。可以与@Autowired或@Resource一起使用,实现依赖注入。 4. @Service:用于标注一个服务层组件。通常用于标识业务逻辑的实现类。 5. @Repository:用于标注一个数据访问组件,即DAO组件。通常用于标识数据访问层的实现类。 6. @Controller:用于标注一个控制器组件,通常用于标识处理请求的类。 7. @Configuration:用于标注一个配置类,通常与@Bean注解一起使用,用于定义Spring的配置信息。 8. @Scope:用于指定bean的作用域,包括singleton、prototype、request、session等。 9. @Value:用于注入属性值,可以从配置文件中读取。 以上只是一些常用的Spring注解,还有其他更多的注解可以用于实现不同的功能。使用这些注解可以简化代码,提高开发效率。 #### 引用[.reference_title] - *1* *2* *3* [Spring常用注解详解大全(建议收藏)](https://blog.csdn.net/m0_51538362/article/details/114828582)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值