SpringBoot-32-常用注解汇总2

简介: SpringBoot-32-常用注解汇总2在上一章节我们已经讲解了SpringBoot中Controller相关注解,没有看的可以了解一下SpringBoot-31-Controller相关注解详解

SpringBoot-32-常用注解汇总2

在上一章节我们已经讲解了SpringBoot中Controller相关注解,没有看的可以了解一下SpringBoot-31-Controller相关注解详解


请求参数类注解

@PathVariable


表示接收请求路径中占位符的值,通过路径映射取值,参数都用 “/” 按照约定的顺序拼接在方法后面,格式为,格式如下:

@PathVariable("id")
通过@PathVariable,可以将URL中的占位符{id}绑定到处理器类的方法
@GetMapping("/variable/{id}/{name}")
请求路径:http://localhost:8888/request/variable/1/james


实现代码如下

    @GetMapping("/variable/{id}/{name}")
    public String Test(@PathVariable("id")String id,@PathVariable("name")String name){
        return "id: "+id +" name: "+name;
    }



注意如下:

测试结果如下:






fde73e5baa2ee908002a39c69266c027.png

@RequestParam

@RequestParam主要用于将请求参数区域的数据映射到控制层方法的参数上,,使用键值对方式取值,方法名后面加 “?” 开始,多个参数用 “&” 拼接,格式如下

@RequestParam(value = "id",required = false,defaultValue ="1")
请求路径:http://localhost:8888/request/param?name=param


代码实现如下

    @GetMapping("/param")
    public String param(@RequestParam(value = "id",required = false,defaultValue ="1")String id,
                        @RequestParam(value = "name",required = true)String name){
        return "id: "+id +" name: "+name;
    }



注意:**@RequestParam**有四个参数


name:绑定参数的名称


value:和参数name表示的意思一样是name的别名


required:标记参数是否是必须的


defaultValue:如果请求中没有这个参数,那么就使用默认值


测试结果如下:


测试链接:http://localhost:8888/request/param?name=james


f43e6bc54f68d3091107bbeabb59de91.png


@RequestHeader

@RequestHeader把Request请求header部分的值绑定到方法的参数上,也有四个参数和@RequestParam参数含义一样

代码实现如下

    @GetMapping(value="/header")
    public String header(
            @RequestHeader("User-Agent") String userAgent,
            @RequestHeader(value="Accept") String[] accepts){
        return "User-Agent: "+userAgent+"  accept:  "+accepts.toString();
    }



我们使用浏览器测试连接http://localhost:8888/request/header

结果如下:


0747d03870642f5a52b7108928990ab1.png

@CookieValue

@CookieValue绑定Cookie数据值也有四个参数和@RequestParam参数含义一样

代码如下:

    @GetMapping(value="/cookie")
    public String Cookie(
            @CookieValue(value="SESSIONID", defaultValue="") String SESSIONID){
        return "SESSIONID: "+SESSIONID;
    }

测试结果:因为我们Cookie为空,所以返回结果如下:

@Configuration相关注解



@Configuration

@Configuration注解是在Spring 3.0开始添加进去的,用来代替applicationContext.xml配置文件,所以只要是这个配置文件可以实现的事情,都可以通过这个注解在类中进行注册相当于标签。

例子

@Configuration
public class MyConfigTest {
    public MyConfigTest(){
        System.out.println("my config test");
    }
}



启动程序,springboot容器初始化时就自动加载这个类了

@Bean注解


@Bean注解使用在方法上面,相当于之前配置文件.xml中的标签,用于注册bean对象,一般是和**@Configuration**注解配合使用的。

    @Bean
    public String configtest(){
        return "hello config bean";
    }



@Autowired

@Autowired 是根据 类型 (byType)注入的 ,然后在找到type类型的bean时,如果发现有异常(不唯一等),会再去根据name去找bean注入


  • 在Controller中获取并使用我们的configtest的bean,代码如下
@RestController
public class ConfigController {
    @Autowired
    private String configtest;
    @GetMapping("beanconfig")
    public String beanconfig(){
        return configtest;
    }
}



  • 测试结果:

@Qualifier注解


当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用

  • 添加配置类
@Data
public class TestConfigurationProperties {
    private String  epochStr;
    private String timeBits;
    private String workerBits;
    private String seqBits;
}



  • 在MyConfigTest类中注入bean
    @Bean("testconfigurationproperties2")
    public TestConfigurationProperties testConfigurationProperties2(){
        TestConfigurationProperties properties = new TestConfigurationProperties();
        properties.setEpochStr("test2");
        properties.setSeqBits("test2");
        properties.setTimeBits("test2");
        properties.setWorkerBits("test2");
        return properties;
    }
    @Bean("testconfigurationproperties3")
    public TestConfigurationProperties testConfigurationProperties3(){
        TestConfigurationProperties properties = new TestConfigurationProperties();
        properties.setEpochStr("test3");
        properties.setSeqBits("test3");
        properties.setTimeBits("test3");
        properties.setWorkerBits("test3");
        return properties;
    }


  • 在controller中实现
    @Autowired
    @Qualifier("testconfigurationproperties2")
    private TestConfigurationProperties configurationProperties2;
    @Autowired
    @Qualifier("testconfigurationproperties3")
    private TestConfigurationProperties configurationProperties3;
    @GetMapping("/configproperties2")
    public String configproperties2(){
        return configurationProperties2.toString();
    }
    @GetMapping("/configproperties3")
    public String configproperties3(){
        return configurationProperties3.toString();
    }


  • 测试结果

分别访问http://localhost:8888/configproperties2和http://localhost:8888/configproperties2展示测试结果

928046a48ce558abe6e8042ed4277070.png

d2928b52f02eec697f3e46c8d17ccc4d.png


@Resource


@Resource根据Bean的name去获取bean**不像@Autowired **是通过找type类型的bean时,如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了



  • controller代码实现如下
    @Resource(name = "testconfigurationproperties3")
    private TestConfigurationProperties configurationProperties4;
    @GetMapping("/configurationProperties4")
    public String configurationProperties4(){
        return configurationProperties4.toString();
    }



  • 测试结果如下


04f86d33a7928d61d4f6468f409ed0ff.png


Properties使用的相关注解


====================


@PropertySource

我们在开发的时候经常使用配置文件,使用@PropertySource注解我们可以注册一个配置文件,一般和@Configuration配合使用。


在src\main\resources文件夹下添加test.properties属性文件


test.epochStr=2019-12-29
test.timeBits=30
test.workerBits=32
test.seqBits=1


  • 注册Properties文件,一般和@Configuration注解配合使用
@Configuration
@PropertySource("classpath:test.properties")
public class Testproperties {
}



注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,则必须指定properties文件


@Value注解

将test.properties文件中的属性,赋值给普通变量,可以直接在变量声明之上添加@Value()注解:

@Data
@Configuration
@PropertySource("classpath:test.properties")
public class Testproperties {
    @Value("${test.epochStr}")
    private String  epochStr;
    @Value("${test.timeBits}")
    private String timeBits;
    @Value("${test.workerBits}")
    private String workerBits;
    @Value("${test.seqBits}")
    private String seqBits;
}

在Controller中获取并使用我们的Testproperties的bean,代码如下

@RestController
public class PropertyController {
    @Autowired
    private Testproperties testproperties;
    @GetMapping("/properties")
    public String testproperties(){
        return testproperties.toString();
    }
}


  • 测试结果

@ConfigurationProperties


@ConfigurationProperties默认读取的就是application.yml或者application.properties文件和@PropertySource注解很相似

  • application.yml中配置如下
server:
  port: 8888
uid:
  epochStr: 'yml'
  timeBits: 30
  workerBits: 32
  seqBits: 1



  • 使用@ConfigurationProperties注解结合@Configuration将我们的属性封装成Bean
@Data
@Configuration
@ConfigurationProperties(prefix = "uid")
public class UidConfigurationProperties {
    private String  epochStr;
    private String timeBits;
    private String workerBits;
    private String seqBits;
}


  • 在Controller中获取并使用我们的TestConfigurationProperties的bean,代码如下
    @Autowired
    private UidConfigurationProperties uidConfigurationProperties;
    @GetMapping("/uid")
    public String uid(){
        return uidConfigurationProperties.toString();
    }
  • 测试结果

目录
相关文章
|
2月前
|
Java 开发者 Spring
【SpringBoot 异步魔法】@Async 注解:揭秘 SpringBoot 中异步方法的终极奥秘!
【8月更文挑战第25天】异步编程对于提升软件应用的性能至关重要,尤其是在高并发环境下。Spring Boot 通过 `@Async` 注解简化了异步方法的实现。本文详细介绍了 `@Async` 的基本用法及配置步骤,并提供了示例代码展示如何在 Spring Boot 项目中创建与管理异步任务,包括自定义线程池、使用 `CompletableFuture` 处理结果及异常情况,帮助开发者更好地理解和运用这一关键特性。
125 1
|
2月前
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
2月前
|
缓存 Java 数据库连接
Spring Boot奇迹时刻:@PostConstruct注解如何成为应用初始化的关键先生?
【8月更文挑战第29天】作为一名Java开发工程师,我一直对Spring Boot的便捷性和灵活性着迷。本文将深入探讨@PostConstruct注解在Spring Boot中的应用场景,展示其在资源加载、数据初始化及第三方库初始化等方面的作用。
53 0
|
9天前
|
Java Spring 容器
Spring使用异步注解@Async正确姿势
Spring使用异步注解@Async正确姿势,异步任务,spring boot
|
8天前
|
XML Java 数据格式
spring复习03,注解配置管理bean
Spring框架中使用注解配置管理bean的方法,包括常用注解的标识组件、扫描组件、基于注解的自动装配以及使用注解后的注意事项,并提供了一个基于注解自动装配的完整示例。
spring复习03,注解配置管理bean
|
9天前
|
XML 前端开发 Java
控制spring框架注解介绍
控制spring框架注解介绍
|
22天前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
2月前
|
Java 数据安全/隐私保护 Spring
揭秘Spring Boot自定义注解的魔法:三个实用场景让你的代码更加优雅高效
揭秘Spring Boot自定义注解的魔法:三个实用场景让你的代码更加优雅高效
|
2月前
|
XML Java 数据库
Spring5入门到实战------15、事务操作---概念--场景---声明式事务管理---事务参数--注解方式---xml方式
这篇文章是Spring5框架的实战教程,详细介绍了事务的概念、ACID特性、事务操作的场景,并通过实际的银行转账示例,演示了Spring框架中声明式事务管理的实现,包括使用注解和XML配置两种方式,以及如何配置事务参数来控制事务的行为。
Spring5入门到实战------15、事务操作---概念--场景---声明式事务管理---事务参数--注解方式---xml方式
|
2月前
|
XML 数据库 数据格式
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
这篇文章是Spring5框架的实战教程的终结篇,介绍了如何使用注解而非XML配置文件来实现JdbcTemplate的数据库操作,包括增删改查和批量操作,通过创建配置类来注入数据库连接池和JdbcTemplate对象,并展示了完全注解开发形式的项目结构和代码实现。
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
下一篇
无影云桌面