Spring @PostConstruct Annotation with Hybris to load configuration

 Spring @PostConstruct Annotation with Hybris

Use Case: loading configuration from Hybris local.propeties file after instance of service class is created instead of loading it every time whenever it is required.


@Service("testDefaultEmailService")
public class TestDefaultEmailService extends DefaultEmailService implements TestEmailService {

@Resource( name = "configurationService")
private ConfigurationService configurationService;

private int maxRetryAttempts;
private int emailRetryDelay;

@PostConstruct
void init(){
maxRetryAttempts = configurationService.getConfiguration().getInt("email.retry.attempts");
emailRetryDelay = configurationService.getConfiguration().getInt("email.retry.interval");
}

@PostConstruct annotation will be called only after dependencies were
 injected into the service class bean either from @Autowired annotations or
 through XML file.

We can not initialize in constructor since during that time dependencies are not added 
and it will result in null pointer exception. Code shown below will not work.
@Service("testDefaultEmailService")
public class TestDefaultEmailService extends DefaultEmailService implements TestEmailService {


@Resource( name = "configurationService")
private ConfigurationService configurationService;

private int maxRetryAttempts;
private int emailRetryDelay;

TestDefaultEmailService (){
maxRetryAttempts = configurationService.getConfiguration().getInt("email.retry.attempts");
emailRetryDelay = configurationService.getConfiguration().getInt("email.retry.interval");
}





Comments

Popular posts from this blog

Hybris / SAP Commerce Cloud Groovy Scripting Job to Generate CSV/Excel Reports and copy to Commerce cloud Blob Storage

Emma's dream - a kids story - By Kavya

Find Duplicate CMSItem in Hybris/SAP Commerce Cloud.