java - @Value("${model.version:2}") 没有占用默认值 = 2
问题描述
我有一个 spring 应用程序,我在其中放置了如下代码,并且我正在传递 mvn 参数来更新值。问题是每次我传递值时,不管它默认取 0 的值。你能帮我解决这个问题吗?
这是我的小代码片段
@Value("${model.version:2}")
private int model;
public test class(){
if(model == 2){
<some logic>
}
}
使用 mvn 参数作为-Dmodel.version=2
解决方案
简而言之:您没有使用弹簧管理的上下文。
让我们一起来看看。
假设一个类MyCoolClass
:
@Component
public class MyCoolClass {
@Value("${some.value:3}")
private int a;
public void show() {
log.info("a is " + a);
}
}
如果您自动装配它并调用 show() 它会记录
a 是 3
现在让我们创建一个测试来验证它是否真的有效:
@SpringBootTest
public class MyTest {
@Autowired
private MyCoolClass myCoolClass;
@Test
public void lookAtMe() {
myCoolClass.show();
}
}
这最初会引发 NPE,因为this.myCoolClass
它是 null;关于某些无法正常工作的第一个提示。让我们克服这一点并实例化myCoolClass
自己:
this.myCoolClass = new MyCoolClass();
this.myCoolClass.show()
a 为 0
这里的线索是,如果您自己创建一个 MyCoolClass 实例,没有人会@Value
为您解析注释并处理表达式。这只是一个普通的POJO。
为了解决这个问题,添加@RunWith(SpringJUnit4ClassRunner.class)
到类和中提琴,日志运行整个 Spring 应用程序启动和日志a is 3
!(当然没有用户创建的构造函数调用):
@SpringBootTest
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
public class mytest {
@Autowired
private MyCoolClass myCoolClass;
@Test
public void lookAtMe() {
myCoolClass.show();
}
}
这就是日志的样子:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.13.RELEASE)
12:41:59 INFO 912 --- [ main] com.example.demo.MyTest : Starting MyTest on clijsters-computer with PID 912 (started by dclijsters in C:\demo)
12:41:59 INFO 912 --- [ main] com.example.demo.MyTest : No active profile set, falling back to default profiles: default
12:42:01 INFO 912 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
12:42:02 INFO 912 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
12:42:02 INFO 912 --- [ main] com.example.demo.MyTest : Started MyTest in 2.513 seconds (JVM running for 3.376)
12:42:02 INFO 912 --- [ main] com.example.demo.MyTest : a is 3
12:42:02 INFO 912 --- [ Thread-3] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
12:42:02 INFO 912 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
推荐阅读
- javascript - 为元数据分配和查询 Javascript 箭头函数
- python - 如何根据其他行值添加熊猫数据框列
- python - 如何将 pandas 行转换为自定义 json 格式并发出 POST 请求
- javascript - 如何使用 PHP/Jquery live 从表单获取输入?
- python - 实现列表/字典理解的 Pythonic 方式
- tfs - nuget凭据如何判断正在使用哪个提供程序?
- javascript - 如何使用 Webpack 包含/导入整个 JS 文件
- linux - Shell脚本未退出while循环
- opengl - 在 OpenGL 中使用 GL_ARRAY_BUFFER 创建索引缓冲区和使用 GL_ELEMENT_ARRAY_BUFFER 创建索引缓冲区之间有什么区别吗?
- rest - Azure DevOps Team Foundation 服务器项目板实时更新?