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; publicclassCommonServiceImplimplementsCommonService { value="${my.name}") (privateStringmyName; publicStringgetMyName() { 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**/"/rest") (publicclassFristController { privateCommonServicecommonService; /*** index* @return*/"/index") (publicStringindex() { commonService.index(); return"hello,frist Controller index"; } "/getName") (publicStringgetName() { return"获取到application中配置的:myname->"+commonService.getMyName(); } }
浏览器输入http://127.0.0.1:8080/rest/getName访问测试一下:
ok,获取到了,方便简洁易用,优秀如我!
控制台也输出了我在Service中打印的信息,完美,下班!