In spring, @ RequestBody is used, and the corresponding bean's attribute name writes are empty.
Recently, the project used the new spring feature @ RequestBody, which is very useful. The json string sent by the client is directly converted and injected to the bean, I used to develop projects according to SUN's java Naming rules. I didn't find any exceptions.
To create a project for the customer, the customer needs to follow the customer's needs. The customer's requirements are not subject to any specification constraints. The requirement is that the first letter of the variable name in the json string is all uppercase and lowercase, if you follow the regular java Naming rules, this is the method to name the class.
After several interfaces are made and tested by myself, I found that the variable passed by the client via @ RequestBody could not be assigned to the corresponding bean. At the moment, I felt a little helpless, if a customer does not issue a card according to the rules, he/she must pay for his/her failure.
After thinking, the Controller class can be named by itself. The specified method is @ Controller ("XXX "), then the variables in the bean corresponding to the json string can also be designated by user, and the answer is finally found after some searches.
1. Correct Solution:
Specify an alias for each attribute. The specified method is similar to controller, as shown below:
public class User {@JsonProperty(value = "Name")private String name;@JsonProperty(value = "Age")private int age;}After the corresponding name is specified, the problem I encountered is solved.
2. analyze the cause of the error:
Because setName (...) is used during injection (...), setSex (...), according to the naming rules of java, the corresponding variables, name and sex will be assigned values, but if the variables are named Name and Sex, although the generated setter function is still setName (...), setSex (...), however, when the spring framework is injected, it cannot tell whether it is name or Name. It will still follow the naming rules, so it will still assign a value to the name. If it does not follow the naming rules, if Name is used, the injection cannot be completed.
3. Conclusion:
If there is no other reason for writing java, it is still written in accordance with java programming specifications. After all, it is a set of customary rules, and everyone is working according to this rule, if you do not play the cards with common sense, the problem is inevitable. It is quite troublesome to solve this problem. After all, no one can change the spring framework.