【SpringBoot】使用属性文件给成员变量配置值对final成员变量是无效的,只对普通成员有效

【结论】

使用属性文件给成员变量配置值对final成员变量是无效的,只对普通成员有效。

【证明】

待注入类Test:

package com.hy.lab.valueinjection;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Test {
    @Value("${test.a}")
    public String a="a";// 普通成员,且属性文件有键值,注入有效

    @Value("${test.b}")// 普通不变成员,属性文件有键值,注入无效
    public final String b="b";
}

属性文件application.properties:

test.a=aa;
test.b=bb;

测试类:

package com.hy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;

@SpringBootApplication
public class MyApplication  implements CommandLineRunner {
    @Autowired
    Test t;

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("a="+t.a);
        System.out.println("b="+t.b);
    }

}

输出:

a=aa;
b=b

由上看a是被注入了aa值,保持原值。

两次试验说明,想给变量注入值,该变量不能被static或final修饰。

END

 

posted @ 2022-07-26 16:07  逆火狂飙  阅读(391)  评论(0)    收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东