Official account: Mufeng Technical Notes

I. Background introduction

In the actual development process, it is often necessary to read configuration files under the Resources folder in the project directory. This paper mainly introduces several methods of reading configuration files in this directory, so that it can be flexibly selected in practical projects. This article describes how to read configuration files in a relative directory. The existing project catalog is as follows:

Second, the specific reading method

1. When you need to read the properties file in the current path, that is, if it is not deployed locally on a specific server:

File file = new File("src/main/resources/test.properties");
InputStream in = new FileInputStream(file);
Copy the code

2. When the project is deployed to the server in the form of war or JAR, when the corresponding properties file needs to be read, the relative path should be adopted at this time. The following is read in stream mode.

As you can see from the above figure, when the project is deployed on the server, the configuration files and the code are in the corresponding classes folder:

InputStream in = this.getClass().getResourceAsStream("/test.properties");
Properties props = new Properties();
InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
props.load(inputStreamReader);
Copy the code

After reading data in this flow mode, obtain the value corresponding to the key in the configuration file by using props. GetProperty (key).

3, we can also use annotations to read configuration files. In the SpringBoot project, there is no need to do the corresponding configuration in the Spring configuration file. You can directly use the annotations to obtain the value corresponding to the key value in the configuration file.

@Value("${local.server.port}")// Inject the port number
private int port;
Copy the code

Note: When value appears in Chinese, the injected value will be garbled. The reason is that The Default Unicode encoding is used when SpringBoot automatically loads application.properties. The solution is as follows:

@RestController
@RequestMapping(value = "/redis")
@PropertySource(value = {"classpath:application.properties"},encoding="utf-8") 
public class UserController extends BaseController{

    @Autowired
    IUserService userService;

    @Autowired
    IRedisService redisService;

    @Value("${amchine.ip}")
    private String ip;
    }
Copy the code

Third, summary

This paper mainly introduces several methods of reading properties files under project Resources directory and matters needing attention. In actual development, you can choose the appropriate way according to your own needs.

Welcome to pay attention to the author’s wechat public number, irregularly share source code analysis, architecture design and other articles, as well as free interview and learning materials to share with you oh.