@Value注解的使用(可用于配置文件) | 您所在的位置:网站首页 › spy注解 › @Value注解的使用(可用于配置文件) |
基本概念
@Value:注入配置文件中的内容。只要是spring的注解类(service,compotent, dao等)中都可以。 @Component:泛指组件,当组件不好归类的时候,可以使用这个注解进行标注。 @AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
所以必须是使用Spring或Spring Boot的注解类,就可以使用@Value注解。 代码与实例(springboot和单元测试) 在【IDEA JAVA Spring Boot运行HelloWorld(1.8)】的基础上增加代码 在application.properties中填入下述内容 testString=demo123
在类Demo中新增如下代码,(可能需要在@Service和@Value上导入类) package com.example.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @Service public class Demo { @Value("${testString}") String testString; @RequestMapping(value = "hello", method = RequestMethod.GET) public String say() { String test = testString; // 打开/关闭注释,IDE会自动导入或删除对应的包 // canner可能对应很多包,可选择import java.util.Scanner; // Scanner sc = new Scanner(System.in); return test; } }在行String test = testString;打一个断点,启动调试模式
在浏览器中输入:http://localhost:8080/hello 进入IDEA中查看变量testString的值,可以看到配置application.properties中的值已经加载到程序中了
在单元测试类DemoApplicationTests中新增如下代码,(可能需要在@SpringBootTest和@Value上导入类) package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; //@SpringBootTest @SpringBootTest(classes = DemoApplicationTests.class) //给测试类提供上下文环境 class DemoApplicationTests { @Value("${testString}") String testString; @Test void test() { String test = testString; } @Test void contextLoads() { } }
可能需要提前了解:JUnit单元测试框架 调试单元测试
查看变量testString的值,可以看到配置application.properties中的值已经加载到程序中了
|
CopyRight 2018-2019 实验室设备网 版权所有 |