卜若的代码笔记系列-Web系列-SpringBoot-第十章:@Value("${}")-3210


卜若的代码笔记系列-Web系列-SpringBoot-第十章:@Value("${}")-3210

问题背景:我们通常会在写服务的时候遇到这样一个需求。
我们配置密码,账号。
为什么会遇到这个需求呢,举个例子,我们想要配置一个登陆的权限
也就是说,你需要输入账号和密码才能登陆这个网站。
我们有很多种办法。
比如:我们可以将这个账号和密码放在数据库里,通过连接数据库
然后进行匹配。
但是,在有的时候,我们其实并不想去连接数据库,我们只想使用一个
txt之类的文件去记录就行。
于是,在这个问题提出之后我们产生了使用@Value("${xx.xxx.xxx}")
来将数据和源代码分离的作用。

算起来,这也算是面向接口的一部分了。


1.springboot里面提供了一个.properties的文件


我们可以在这里面定义一些字段。

比如我的这个项目
图片:

application.properties

我在里面定义一个字段

test.testList.a1 = 9443;

2.通过@Value(${test.testList.a1});
将该值赋给我们定义的一个字段

如:我们在FileController里面定义了一个
String的字段:

private String a1;

现在我们赋值

@Value("${test.testList.a1}")
private String a1;

我们测试下,使用System.out.println(a1);
将数据打印出来;

@RestController
@RequestMapping("/file")
public class FileController {
    
    @Value("${test.testList.a1}")
    private String a1;
    
    
    @RequestMapping("/testValue")
    public void testValue()
    {
        
        
        System.out.print(a1);
    }
}


结果:
图片:


3.现在,我们还有一个问题,假如我们不在application.properties里面定义字段
我们想新建一个password.properties的文件来管理这些字段呢,是不是也可以直接
这样就行了?
我们试试:

    我们尝试添加test.properties文件:

并且将数据test.testList.a1 = 9443放到这个.properties文件

报错

org.springframework.beans.factory.BeanCreationException: Error creating bean with 
name 'fileController': Injection of autowired dependencies failed; nested exception 
is java.lang.IllegalArgumentException: Could not resolve placeholder 'test.testList.a1' 
in value "${test.testList.a1}"

它的意思总结起来就是无法给将test.testList.a1的值送给${test.testList.a1}

显然,它的原因肯定是因为我们没有注册这个test.properties,所以@Value("${}")这个批注就拿不到这个test.properties的内容

所以,我们需要通过正规手段去注册这个.properties。

 

4.注册:

 

怎么注册,当然,通常情况下我们会去想是在web.xml里面去注册,这也是在我在学习mvc后的第一反应,但是在springboot里面

是没有web.xml(它隐藏了,当然,你也可以手动创建,之后肯定是一系列复杂的配置,所以,我们通常会拒绝这种办法)

 

所以,查阅了一些资料:

这样,我们可以将这个类通过

@PropertySource( "classpath:test.properties")


配置它的@Value源,这样我们就能够使用这个.properties的字段了

@PropertySource( "classpath:test.properties")
@RestController
@RequestMapping("/file")
public class FileController {
    
    @Value("${test.testList.a1}")
    private String a1;    
    @RequestMapping("/testValue")
    public void testValue()
    {
        System.out.print(a1);
    }

}

结果:

 5.现在,我们有个新的问题,如果使用这个

@PropertySource( "classpath:test.properties")

批注,那我们还能不能获取到application.properties里面的资源呢?

我们做个试验:

 

答案是可以的!!!!!!!!!!!!!!!!

 

6.我们产生了新的疑问,假如,我要定义一个新的test2.properties可不可以同时使用呢?

我们做个试验:

答案显而易见,可以咯~

ps:我的邮箱[email protected],欢迎有问题的同学发邮件共同交流~ 

 

 

 

 

引用:

http://www.javashuo.com/article/p-yziikwyx-de.html

https://blog.csdn.net/fjnpysh/article/details/74360111