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 wereinjected into the service class bean either from @Autowired annotations orthrough 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
Post a Comment