Create Spring Bean On-Demand using Bean Lookup

Bean Configuration – create prototype method on demand using look-up method

@Configuration
@Lazy(value=true)
public class SalesforceAuthenticationConfigImpl implements SalesforceAuthenticationConfig {

    @Bean(name="loginToProductionSalesforce")
    @Scope(value="prototype")
	public PartnerConnection loginToProductionSalesforce() throws ConnectionException, InterruptedException {
		int retryCounter=1;
		productionPartnerConnection();
		Date now = new Date();		
		while (partnerConnection==null && retryCounter <= RETRYAMOUNT || TimeUnit.MILLISECONDS.toMinutes(now.getTime() - partnerConnection.getServerTimestamp().getTimestamp().getTimeInMillis()) > MINUTESTILLTIMEOUT){
			logger.info("loginToProductionSalesforce retry attempt: " + retryCounter);
			productionPartnerConnection();
        	retryCounter++;
        	Thread.sleep(30*1000);
		}
		return partnerConnection;
	}


    @Bean
	public SalesforceAuthenticationFactory salesforceAuthenicationFactory(){
		return new SalesforceAuthenticationFactory() {
			@Override
			public PartnerConnection createPartnerConnection() throws ConnectionException, InterruptedException {
				return loginToProductionSalesforce();
			}
		};
	}

}

Configuration factory

@Bean
	public SalesforceAuthenticationFactory salesforceAuthenicationFactory(){
		return new SalesforceAuthenticationFactory() {
			@Override
			public PartnerConnection createPartnerConnection() throws ConnectionException, InterruptedException {
				return loginToProductionSalesforce();
			}
		};
	}

Test Class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SalesforceAuthenticationConfigImpl.class})
public class SalesforceAuthenticationServiceTest {

	@Autowired SalesforceAuthenticationFactory salesforceAuthenicationFactory;

     @Test
	public void testSalesforceAuthenitcationFactory(){
		try {
			PartnerConnection pConnection = salesforceAuthenicationFactory.createPartnerConnection();
			assertNotNull(pConnection.getConfig().getSessionId());
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Each time you call createPartnerConnection()() you will receive the reference to newly created instance of PartnerConnection class.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: