I am new to spring boot. I want to achieve relaxed binding in spring boot. As per this documentation https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-relaxed-binding.
It says, even though if we have name with dashes(like first-name) in .properties file, it can be mapped to variable without dashes(like firstName). But it didn't seems to be working.
I have application.properties file like below:
person.first-name=orcl
person.address=xyz
And my Properties util java file looks like:
#ConfigurationProperties(prefix="person")
#Component
#PropertySource("file: application.properties")
public class ApplicationPropertiesUtil
{
private String firstName;
private String address;
public String getfirstName()
{
return firstName;
}
public void setfirstName(String firstName)
{
this.firstName = firstName;
}
public String getaddress()
{
return address;
}
public void setaddress(String address)
{
this.address = address;
}
}
address property is getting bind properly, but for firstname it is null.
The problem is your setter methods which don't align with java bean standard.
It should be named "setFirstName" with an upper case F.
Related
I am trying to declare a component with a parametrized constructor but it is throwing me an error. Is there any way to resolve this situation?
I can have a default constructor to avoid the situation. But, my Business requirement says only to have parametrized constructor. Is there any work around?
#Component
public class Employee {
private String firstName;
private String lastName;
private int yearsOfExperience;
private String designation;
#Autowired
public Employee(**String** firstName, **String** lastName, **int** yearsOfExperience, **String** designation) {
this.firstName = firstName;
this.lastName = lastName;
this.yearsOfExperience = yearsOfExperience;
this.designation = designation;
}
Error: Could not Autowire. No Beans of String is found. The bold text is an error out with a shared message.
I am using jackson 2.10.0 (https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.10.0), following is a simple test case
The Person class is defined as follows, for the setters, I have used the #JsonSetter annotation, and didn't use #JsonGetter for the getters,
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
#JsonSetter("first_name")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
#JsonSetter("last_name")
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Then, I create a Person object ,and serialize it as string,
import com.fasterxml.jackson.databind.ObjectMapper;
public class Person3Test2 {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setFirstName("abc");
p.setLastName("def");
String str = new ObjectMapper().writeValueAsString(p);
System.out.println(str);
}
}
It will call Person's getters, since it doesn't use #JsonGetter, so I think the output should be
{"firstName":"abc","lastName":"def"}
But, I am surprised to find that it is :
{"first_name":"abc","last_name":"def"}
It looks that the #JsonSetter has affected the getter output, I would ask what's the behavior here.
#JsonSetter will effect during serialization also here is the github issue, if you want different name just use another annotation #JsonGetter on get method
Documentation may be wrong; #JsonSetter does not only affect deserialization. While it can indeed be used for asymmetric naming (similar to #JsonProperty itself with "split" annotation), its scope is not limited.
It may have been at some point, but after unification of property handling (in 1.8 or so), there is less separation between various property accessors.
I can review Javadocs to make it clear that none of annotations is strictly limited in scope -- some may only be relevant to one or the other, but none is intentionally separated.
I am making an android application using google Gson to parse to and from json classes that I have in other project.
I have a class Person which contains attributes like:
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
}
But when I'm debugging in the MainActivity.java I see a or b as attribute names instead of firstName and lastName, and that's make the json text be:
{a:"someName", b:"someLastName"}
does anyone know's why is this and how can I fix it?
class Person.java is located in a separated project. I think that my project can't see the source code and that would be the reason.
I'm kind of lost here.
Thank you
Using Spring data I would like to be able to define a custom get-method inside a domain model class without affecting the model itself. For example, using this model:
#Document
public class Person
{
private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
Eveything is working fine so far: the model Person has the fields 'firstName' and 'lastName' and I can successfully save a 'person'. The resulting JSON has the fields 'firstName' and 'lastName'. Now I would like to add some additional data in the JSON without affecting the model and its save-operations, something like this:
#Document
public class Person
{
private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
// custom method
public String getFullName()
{
return firstName+" "+lastName;
}
}
The JSON should contain the same data as before, but this time also an additional 'fullName'-field. However, at the same time the data model assumes an additional field 'fullName' is added and filled with null-values when saving into the database.
I have already tried annotations like #Transient, but this does not work. The documentation states "by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database", so it only can be applied to private fields in the class, not to get-methods.
What is the correct way to do this in Spring? Of course I can extend the class Person and include the getFullName-method there, but I was wondering if it is possible to include everything in one class.
Edit:
I use Elasticsearch as DB engine using spring-data-elasticsearch 1.2.0.RELEASE. I have just tested MongoDB as alternative and then it is working fine, even without the #Transient annotation. I think the index-method of the ElasticsearchRepository is serializing the provided class instance when saving it to the database. In that way the JSON-output and the saved data are always identical. Any suggestions?
As the title says, there has always been quite a discussion about getters and setters in any programming language, so also Java.
The question is the following: Are there any new arguments since Java 8 got released?
An example of an already existing argument is that getters and setters encapsulate state, or that they make it possible to change the implementation without changing the API.
Yes, there are! Since Java 8 method references were introduced, and as their name says, they can only be used with methods.
Consider the following code:
class Person {
private String firstName;
private String lastName;
public Person(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
Assume we want to obtain a map that contains a lists of people grouped by their last name, we can only do that via method references with the following code:
List<Person> personList = new ArrayList<>();
personList.add(new Person("Shannon", "Goldstein"));
personList.add(new Person("Donnie", "Denney"));
personList.add(new Person("Mark", "Thomas"));
personList.add(new Person("Julia", "Thomas"));
Map<String, List<Person>> personMapping = personList.stream()
.collect(Collectors.groupingBy(Person::getLastName));
System.out.println("personMapping = " + personMapping);
Which prints out, formatted nicely:
personMapping = {
Thomas=[Mark Thomas, Julia Thomas],
Goldstein=[Shannon Goldstein],
Denney=[Donnie Denney]
}
This would not have worked if we were using public variables, as you cannot obtain a method reference on them, nor reference them in another way other than writing a full-fledged lambda where it is not neccessary.
(For curious people: person -> person.lastName would need to have been used)
Also, keep in mind that this answer differs from someone claiming that if an object needs to adhere to a certain interface, that then getters and setters must be used. As in this example the Person class adheres to no interface, yet benefits from having getters available.
public class Customer {
private String email;
public void setEmail(String email) { this.email = email; }
public String getEmail() { return email; }
}