Generating Getters/Setters in Spring STS

0Shares

If you create a class with private fields and you now needs to assign values from outside the class, you can achieve the same with two methods:

1. Create a parameterized constructor and asking the properties to the private fields.
2. Create Setters/Getters for the fields.

If you are using Spring STS or any eclipse based tools for writing this code, you do not need to do it by hand as eclipse by default provides the option to generate the Setters/Getters for the fields.

Let us assume the class created is as below:

package com.bankaccount.model;

public class AccountHolder {

	private String accountHolderFirstName;
	
	private String accountHolderLastName;
	
	private String accountHolderMiddleName;
}

Figure 1: Original source code before generating Getters and Setters for the Private fields

Now if you want to create getters/setters in eclipse, you can do that by selecting one of the field name and right-click, a context menu will appear. Then select “Source” and then select “Generate Getters and Setters” option.

It shows a dialog with getter and setter for the first property or that you highlighted in your class. In our example, we need for all the private properties and so click “Select All” button and click “OK” button.

Generating Getters and Setters...

Figure 2: Showing option to select “Generate Getters and Setters…”

After the Getters and Setters are generated, then your code should look like as below  with the Setters and Getters generated for all the fields:

package com.bankaccount.model;
	
	public class AccountHolder {
	
		private String accountHolderFirstName;
		
		public String getAccountHolderFirstName() {
			return accountHolderFirstName;
		}
	
		public void setAccountHolderFirstName(String accountHolderFirstName) {
			this.accountHolderFirstName = accountHolderFirstName;
		}
	
		public String getAccountHolderLastName() {
			return accountHolderLastName;
		}
	
		public void setAccountHolderLastName(String accountHolderLastName) {
			this.accountHolderLastName = accountHolderLastName;
		}
	
		public String getAccountHolderMiddleName() {
			return accountHolderMiddleName;
		}
	
		public void setAccountHolderMiddleName(String accountHolderMiddleName) {
			this.accountHolderMiddleName = accountHolderMiddleName;
		}
	
		private String accountHolderLastName;
		
		private String accountHolderMiddleName;
	}

Figure 3: Code after Getters and Setters generated

Hope this helps!

0Shares