Java-SpringBoot-05-使用@Value注解注入单个应用程序参数

简介: SpringBoot中可以使用使用@Value注解注入单个应用程序参数,很方便的在业务类中使用。

 SpringBoot中可以使用使用@Value注解注入单个应用程序参数,很方便的在业务类中使用。

       方式是在配置文件中配置一个值,然后在业务流程中通过@Value注解将值注入类中,从而获取到并使之能在业务流程中使用。

一、application.properties中配置name名

#配置namemy.name=xinghua

二、在Service类中直接使用@Value注入

packagecom.xing.studyboot.rest.service.impl;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Service;
importcom.xing.studyboot.rest.service.CommonService;
@ServicepublicclassCommonServiceImplimplementsCommonService {
@Value(value="${my.name}")
privateStringmyName;
@OverridepublicStringgetMyName() {
System.out.println("获取到application中配置的:myname="+myName);
returnmyName;
  }
}

就这么简单!现在在Service中已经获取到了值。

三、从Controller中调用一下,发布一个服务

packagecom.xing.studyboot.rest.controller;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importcom.xing.studyboot.rest.service.CommonService;
/***  第一个测试服务* @author xing**/@RestController@RequestMapping("/rest")
publicclassFristController {
@AutowiredprivateCommonServicecommonService;
/*** index* @return*/@RequestMapping("/index")
publicStringindex() {
commonService.index();
return"hello,frist Controller index";
  }
@RequestMapping("/getName")
publicStringgetName() {
return"获取到application中配置的:myname->"+commonService.getMyName();
  }
}

浏览器输入http://127.0.0.1:8080/rest/getName访问测试一下:

image.png

ok,获取到了,方便简洁易用,优秀如我!


控制台也输出了我在Service中打印的信息,完美,下班!

image.png

目录
相关文章
|
3天前
|
Java 编译器 程序员
java注解浅述
java注解浅述
12 1
|
3天前
|
运维 Java 程序员
Spring5深入浅出篇:基于注解实现的AOP
# Spring5 AOP 深入理解:注解实现 本文介绍了基于注解的AOP编程步骤,包括原始对象、额外功能、切点和组装切面。步骤1-3旨在构建切面,与传统AOP相似。示例代码展示了如何使用`@Around`定义切面和执行逻辑。配置中,通过`@Aspect`和`@Around`注解定义切点,并在Spring配置中启用AOP自动代理。 进一步讨论了切点复用,避免重复代码以提高代码维护性。通过`@Pointcut`定义通用切点表达式,然后在多个通知中引用。此外,解释了AOP底层实现的两种动态代理方式:JDK动态代理和Cglib字节码增强,默认使用JDK,可通过配置切换到Cglib
|
2天前
|
Java
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
|
2天前
|
Java Kotlin
关于Java:public函数公开其public / * package * /’参数类型
关于Java:public函数公开其public / * package * /’参数类型
9 3
|
2天前
|
ARouter Java
Java注解之编译时注解
Java注解之编译时注解
16 3
|
3天前
|
存储 缓存 Java
【JavaEE】Spring中注解的方式去获取Bean对象
【JavaEE】Spring中注解的方式去获取Bean对象
3 0
|
3天前
|
存储 Java 对象存储
【JavaEE】Spring中注解的方式去存储Bean对象
【JavaEE】Spring中注解的方式去存储Bean对象
7 0
|
3天前
|
Java 编译器 C语言
【Java开发指南 | 第五篇】Java变量类型、参数变量及局部变量
【Java开发指南 | 第五篇】Java变量类型、参数变量及局部变量
12 3
|
3天前
|
Java 编译器 开发者
Java一分钟之-Java注解的理解与应用
【5月更文挑战第12天】本文介绍了Java注解的基础知识和常见应用,包括定义、应用和解析注解。注解在编译检查、框架集成和代码生成等方面发挥重要作用。文章讨论了两个易错点:混淆保留策略和注解参数类型限制,并提供了避免策略。提醒开发者避免过度使用注解,以保持代码清晰。理解并恰当使用注解能提升代码质量。
13 3
|
3天前
|
Java API Python
java注解
java注解

热门文章

最新文章