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 use @ Value

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to use @ Value". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. String type

First of all, let's create a spring boot project. No, you can take a look at another blogger's article, idea, to create a Springboot 2.x project.

Then configure the following in application.yaml

Chilx: person:name: chilxage: 18

Then we can use these two parameters.

Create a Person class that can be annotated with @ Value

@ Value ("${chilx.person.name}") private String name;@Value ("${chilx.person.age}") private Integer age

Sister Lin: OK, I'll try

After a while-

Sister Lin: that's not right. I reported the wrong project here.

Blogger: let me see. (after a glance) you are such a little fool. Look at the error prompt. You are using undeclared parameters.

I forgot to tell you that we will report an error when we use @ Value to refer to undeclared parameters.

For example, the property gender is not declared in the configuration file, so let's add the following to the Perso class

@ Value ("${chilx.person.gender}") private String gender

Starting the project will report the following error

Sister Lin: is there a solution?

Of course there is. We can give a default value when referencing the property, and assign the default value when the attribute does not exist.

Let's modify what we just did and add a colon and default value after the reference parameter.

/ / default is empty string @ Value ("${chilx.person.gender:}") private String gender1;// default is null@Value ("${chilx.person.nikeName:null}") private String gender2;// default is male @ Value ("${chilx.person.password:' male'}") private String gender3

This problem was easily solved just now.

Well, the basic use of @ Value is over. Is there anything you don't understand?

Sister Lin: no, I already understand the basic use now

Blogger: OK, let's move on.

2. Array type

Next, let's take a look at array types.

Add a configuration to the configuration file

Chilx: person:.... hobbies: basketball, football, games

Add to the Person class

@ Value ("${chilx.person.hobbies}") private String [] hobbies

And then it's okay. It's easy.

Sister Lin: mm-hmm. It's simple. I know all the routines.

Blogger: look at you. Keep going.

3. List/Set collection type

Next, let's learn about collection types. List and Set are used the same way, but Set will repeat them.

Continue to add configurations in application.yaml

Chilx: person:....friend: Xiao Ming, Xiao Hong

Sister Lin: I know how to do it. Isn't it the same as the Array type? who doesn't know it yet? just add it to the Person class. The following will do.

@ Value ("${chilx.person.friend}") private List friend

In the proud start-up project... Successful execution

What do you think? am I good?

Blogger: awesome, you also know that when the attribute does not exist, directly referencing the property will report an error, the collection type you know how to

Sister Lin: well, I don't know. (whisper)

Blogger: ha, you still have to show off. Now you know your shortcomings.

Sister Lin: Oh, don't talk about me. Tell me how to handle it.

Blogger: OK, OK, I'll tell you not to hit me. You should take a good look at the following code, which can be roughly divided into the following situations

/ / default value [] @ Value ("${chilx.person.friend1:}") private List friend1;// default value [null] @ Value ("${chilx.person.friend1:null}") private List friend2;// default value [Xiao Ming, Xiao Hong] @ Value ("${chilx.person.friend1: Xiao Ming, Xiao Hong}") private List friend3 / / the following is the EL expression / / default value [] @ Value ("# {${chilx.person.friend1:} '.split (',')}) private List friend4;// default value [null] @ Value (" # {${chilx.person.friend1:null} '.split (',')} ") private List friend5 / / default value [Xiao Ming, Xiao Hong] @ Value ("# {'${chilx.person.friend1: Xiao Ming, Xiao Hong} '.split (',)}") private List friend6;// default value [] @ Value ("# {${chilx.person.friend1:,} '.split (',')}") private List friend7

Sister Lin: I see. I see. That's what it is. Hey, that's not right. Why didn't you tell me about the default value of Array?

Blogger: yes, I thought you ignored this problem.

Sister Lin: why are you doubting me?

Blogger: no, the reason I didn't say before is that I thought Array,List and Set are the same in default values.

In fact, there are several other injection types of collection types, but you cannot annotate them with @ Value.

I'll give you more details when I finish telling you about the Map type.

Come on, let's move on.

4. Map type

Next, let's talk about dictionary types.

Sister Lin: (whispering) it's not all the same routine. Who doesn't know yet?

The blogger pretended not to hear...

First add the configuration to the configuration file

Chilx: person: .pet: "{'puppy': 'Wangwang', 'kitten': 'meow'}" courses: "{'Chinese': 100,' math': 99}"

Add the corresponding attribute to the java class, and note that the EL expression is used in @ Value

@ Value ("# {${chilx.person.pet}}") private Map pet;@Value ("# {chilx.person.courses}}") private Map courses

That's it, isn't it simple?

Sister Lin: yes.

By the same token, let's talk about the default value of Map.

/ / default value null@Value ("# {${chilx.person.courses1: {}") private Map courses1;// default value null@Value ("# {${chilx.person.courses1:null}}") private Map courses2;// default value {k1:v1} @ Value ("# {${chilx.person.courses1: {K1V1V1}") private Map courses3

As you can see, the settings of the default values are more or less the same

Dictionary types are the same as collection types, there are other configuration methods, but the @ Value injection method is not supported. Let's continue after a break.

Spring to autumn, ten eyes in the twinkling of an eye. Ahem, it's too far. Go on.

5 、 ConfigurationProperties

Didn't we talk about set types and dictionary types and other injection methods before? now let's learn while the iron is hot.

The method we are using now is to batch bind properties in the configuration file.

Add related dependencies to pom.xml

Org.springframework.boot spring-boot-configuration-processor true

Create a new class User

Add the corresponding class comments, and the prefix attribute corresponds to the configuration level in the configuration file, up to the penultimate level.

@ ConfigurationProperties (prefix = "chilx.girlfriend")

Write a configuration file

Chilx: girlfriend: name: sister Lin age: 18 hobbies: sing, dance friend: welcome spring, cherish spring pet1: elephant, lion pet2:-tiger-leopard pet3: kitten and puppy courses: K1: 100K2: 100

Write User classes

Note: the properties in the class should be the same as the configuration name at the last level in the configuration file, and keep in mind. If the corresponding configuration does not exist, the property is null

The User class is as follows

@ Component@Getter@Setter@ToString@ConfigurationProperties (prefix = "chilx.girlfriend") public class User {private String name;private Integer age;/** * default is empty string * / private String gender;/** * does not exist as null * / private String nikeName;/** * default is male * / private String password;private String [] hobbies;private List friend;private List pet1;private List pet2;private List pet3;private Map courses

After completing the above steps, the property binding is completed, isn't it simple?

Sister Lin: yes, it is. It feels much more convenient than @ Value. It can be bound in batches at once, but it is not as flexible as @ Value.

Blogger: you can't have both a fish and a bear's paw.

ConfigurationProperties can bind not only properties but also objects. I'll show you.

Add the following configuration to the configuration file

Chilx: girlfriend:. Boyfriend: {name: chilx, age: 18}

Add the corresponding attribute to the User class

Private Boyfriend boyfriend

The above two steps have been solved. Is it very simple? is it very simple?

@ Value and ConfigurationProperties are different.

@ value property padding is called populateBean () after bean instantiation, which is populated by AutowiredAnnotationBeanPostProcessor injection.

The @ ConfigurationProperties attribute is populated by ConfigurationPropertiesBindingPostProcessor injection when initializeBean

Conclusion: if a field is populated in both ways, the final padding is determined by @ ConfigurationProperties

That's all for "how to use @ Value". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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