Home >Java >javaTutorial >How to solve the problem of using @Value in springBoot

How to solve the problem of using @Value in springBoot

王林
王林forward
2023-05-14 18:55:061456browse

Problems arising from using @Value to obtain values

In the springBoot project, we generally write some paths or resources in the configuration file to facilitate management.

But there may be some problems when obtaining it.

file.uploadFolder=E://upload/

1. Generally define a field

use @Value("$ {name}") can get the value

@Value("${file.uploadFolder}")
    private String uploadFolder;

2. But usually we will use it in tool classes

But the field is modified by static to become a static variable. Using this method If the value cannot be obtained, what we get is null.

So we have to change the way to get the value, which can be obtained as follows. Remember not to use static in the set method! ! !

private static String uploadFolder;
public static String getUploadFolder() {
        return uploadFolder;
    }
    @Value("${file.uploadFolder}")
    public  void setUploadFolder(String uploadFolder) {
        Base64Utils.uploadFolder = uploadFolder;
    }

3. It is best to add @Component or other annotations

to the tool class so that it can be managed by spring.

Remember the oolong that occurred when springBoot used @Value

Look at the code first

server.port=8007
#mysql配置
url=jdbc:mysql://localhost:3306/lzy_zyg?useUnicode=true&characterEncoding=UTF-8
username=root
password=root

This is the relevant configuration information filled in application.properties, in which the mysql configuration is used as an external Configuration information is used.

Then use it where needed as follows

@Configuration
public class JfinalDb
{
    @Value("${url}")
    private String dbUrl;
    @Value("${username}")
    private String dbUName;
    @Value("${password}")
    private String dbPwd;
...
}

A very strange problem occurs when using it, that is, the username and password of the naming settings are correct, and the local connection is also correct, but always It is an error that the connection authentication failed, and the user name is not root.

Finally I printed out dbUName and found that was not root at all, but my host name!

So here, remember not to customize the name username in the application.properties file, because you will not get the results you want.

The above is the detailed content of How to solve the problem of using @Value in springBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete