Generate Interface from Implementation class using Spring STS

0Shares

Lets say I have an implementation class already defined and now to be able to support SOLID principles, now I need to expose an interface for the implementation class so that we can perform the dependency injection.

My existing class looks like this:

package com.bankaccountholder.dal;

import java.util.ArrayList;
import java.util.List;

import com.bankaccount.model.AccountHolder;

public class AccountHolderRepositoryImplementation {
	
	public List<AccountHolder> findAccountHolders()
	{
		List<AccountHolder> accountHolders = new ArrayList<AccountHolder>();
		
		AccountHolder accountHolder = new AccountHolder();
		accountHolder.setAccountHolderFirstName("FirstName");
		accountHolder.setAccountHolderLastName("LastName");
		accountHolder.setAccountHolderMiddleName("MiddleName");
				
		accountHolders.add(accountHolder);
		
		return accountHolders;
		
	}
	
}

Figure 1: Before interface creation

Now if you want to generate interface for the implementation class, right click on the implementation class name, select “Refactor” in the context-menu and select “Extract Interface” and give the name to the interface and select the methods needed to be declared in the interface and click “OK” as below:

Extract Interface

Figure 2: Extract Interface

Generate InterfaceFigure 3: Generate Interface

Now your implementation class should look be implementing the Interface that you have created as below:

package com.bankaccountholder.dal;

import java.util.ArrayList;
import java.util.List;

import com.bankaccount.model.AccountHolder;

public class AccountHolderRepositoryImplementation implements AccountHolderRepositoryInterface {
	
	/* (non-Javadoc)
	 * @see com.bankaccountholder.dal.AccountHolderRepositoryInterface#findAccountHolders()
	 */
	public List<AccountHolder> findAccountHolders()
	{
		List<AccountHolder> accountHolders = new ArrayList<AccountHolder>();
		
		AccountHolder accountHolder = new AccountHolder();
		accountHolder.setAccountHolderFirstName("FirstName");
		accountHolder.setAccountHolderLastName("LastName");
		accountHolder.setAccountHolderMiddleName("MiddleName");
				
		accountHolders.add(accountHolder);
		
		return accountHolders;
		
	}
	
}

Figure 4: Implementation class now implementing the interface

Also a new interface file will be created and listed in the IDE folder structure as below:

package com.bankaccountholder.dal;

import java.util.List;

import com.bankaccount.model.AccountHolder;

public interface AccountHolderRepositoryInterface {

	List<AccountHolder> findAccountHolders();

}

Figure 5: New interface created

0Shares