Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to read properties or yml file data and match

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to read properties or yml file data and match, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Read properties or yml file data and match

There are several ways to get the data of the configuration file using springboot, including the annotation @ Value, where the content of the configuration file is obtained through IO.

Previously, xx or yy can be set in bean in another test.xml file. Here, if it is not set in the test.xml file, it can be set in the application.* file.

As follows:

Try {InputStream stream = getClass (). GetClassLoader (). GetResourceAsStream ("application.properties"); if (stream = = null) {stream = getClass (). GetClassLoader (). GetResourceAsStream ("application.yml"); InputStreamReader in = new InputStreamReader (stream, "gbk"); BufferedReader reader = new BufferedReader (in); String line While ((line = reader.readLine ())! = null) {if (line.trim (). Split (":") [0] .contentEquals ("xx")) {/ / can be read in test.xml and passed through set. You can also pass the value this.setXX (line.trim (). Split (":") [1] .trim () by setting the set method of the corresponding parameter. } else if (line.trim (). Split (":") [0] .contentEquals ("yy") {this.setYY (line.trim (). Split (":") [1] .trim ()) } else {InputStreamReader in = new InputStreamReader (stream, "gbk"); BufferedReader reader = new BufferedReader (in); String line While ((line = reader.readLine ())! = null) {if (line.trim (). Split ("=") [0] .contentEquals ("xx")) {/ / can be read in test.xml and passed through set. You can also pass the value this.setXX (line.trim (). Split (":") [1] .trim () by setting the set method of the corresponding parameter. } else if (line.trim (). Split ("=") [0] .contentEquals ("yy") {this.setYY (line.trim (). Split (":") [1] .trim ()) } catch (FileNotFoundException e) {logger.error ("cannot find application.* file", e);} catch (IOException e) {logger.error ("there is a problem reading the ip or port of the configuration file", e) } Summary of 1-@value@Value ("${keys}") private String key in several ways to read yml,properties configuration file

What needs to be noted here is that

The current class is to be managed by spring

@ Value does not assign values to static-decorated variables.

Because the @ Value dependency injection of Spring depends on the set method, and the automatically generated set method is a common object method, you assign values to instance variables in ordinary object methods, not static variables, static-modified variables, generally do not generate set methods. If you must assign a value to an attribute modified by static, you can refer to the following method

Private static String url; / / remember to remove static @ Value ("${mysql.url}") public void setDriver (String url) {JdbcUtils.url= url;}

But there is a drawback to this solution. How should arrays be injected?

2-use object injection auth: clients:-id:1 password: 123-id: 2 password: 123@Component@ConfigurationProperties (prefix= "auth") public class IgnoreImageIdConfig {private List clients = new ArrayList ();}

Use the configuration Javabean form to get the value, it is worth noting that the reference name in the object ('clients') must be the same as the (' clients') in the yml file, otherwise the data will not be fetched. Another point is that the array object must be new out first, and the value will fail if there is no object. (in the same way, the map form must first new the object corresponding to map).

3-read configuration file private static final String FILE_PATH = "classpath:main_data_sync.yml"; static Map result = null; private static Properties properties = null; private YmlUtil () {} / * read yml configuration file data * @ param filePath * @ param keys * @ return * / public static Map getYmlByFileName (String filePath, String... Keys) {result = new HashMap (16); if (filePath = = null) {filePath = FILE_PATH;} InputStream in = null; File file = null; try {file = ResourceUtils.getFile (filePath); in = new BufferedInputStream (new FileInputStream (file)); Yaml props = new Yaml () Object obj = props.loadAs (in, Map.class); Map param = (Map) obj; for (Map.Entry entry: param.entrySet ()) {String key = entry.getKey (); Object val = entry.getValue () If (keys.length! = 0 & &! keys [0] .equals (key)) {continue;} if (val instanceof Map) {forEachYaml (key, (Map) val, 1, keys);} else {String value = val = = null? Null: JSONObject.toJSONString (val); result.put (key, value);} catch (FileNotFoundException e) {e.printStackTrace ();} return result;} public static Map forEachYaml (String keyStr, Map obj, int I, String... Keys) {for (Map.Entry entry: obj.entrySet ()) {String key = entry.getKey (); Object val = entry.getValue (); if (keys.length > I & &! Keys [I] .equals (key)) {continue;} String strNew = "" If (StringUtils.isNotEmpty (keyStr)) {strNew = keyStr + "." + key;} else {strNew = key;} if (val instanceof Map) {forEachYaml (strNew, (Map) val, + + I, keys) } else {String value = val = = null? Null: JSONObject.toJSONString (val); result.put (strNew, value);}} return result } / * get Properties type attribute value * @ param filePath classpath: file name * @ param key key value * @ return * @ throws IOException * / public static String getProperties (String filePath,String key) throws IOException {if (properties = = null) {Properties prop = new Properties (); / / InputStream in = Util.class.getClassLoader (). GetResourceAsStream ("testUrl.properties") InputStream in = new BufferedInputStream (new FileInputStream (ResourceUtils.getFile (filePath)); prop.load (in); properties = prop;} return properties.getProperty (key);} public static void main (String [] args) {/ * Map cId = getYmlByFileName ("classpath:test.yml", "auth", "clients") / / cId.get ("") String json = cId.get ("auth.clients"); List maps = JSONObject.parseArray (json, Map.class); System.out.println (maps); * / try {String properties = getProperties ("classpath:test.properties", "fileServerOperator.beanName"); System.out.println (properties) } catch (IOException e) {e.printStackTrace ();} auth: # Authentication clients:-id: 1 secretKey: ba2631ee44149bbe # key key-id: 2 secretKey: ba2631ee44149bbe # key key after reading the above, do you have any further understanding of how to read properties or yml file data and match? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report