首页 > 解决方案 > @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

标签: javaspringspring-bootjvm

解决方案


简而言之:您没有使用弹簧管理的上下文。

让我们一起来看看。

假设一个类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'

推荐阅读