Reputation: 1816
I have a class looking like below
@Component
public class BillDAO {
private DynamoDBMapper dynamoDBMapper;
public void create(BillDO billDO) {
AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1);
DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(builder.build());
dynamoDBMapper.save(billDO);
}
}
Basically, I don't want to construct dynamoDBMapper and builder instance every time I call the method create. Rather like to inject these as beans. What can be done?
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.tarkshala" />
</beans>
I did find few example which use constructor-arg for beans and factory-methods. Not sure how to use that here.
Upvotes: 0
Views: 1424
Reputation: 973
You should be able to make use of @Configuration annotation to do this. Here is the code example of @Configuration implementation to create both AmazonDynamoDBClientBuilder & DynamoDBMapper as Spring beans.
package com.tarkshala;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigurationAnnotationExample {
@Bean
public AmazonDynamoDBClientBuilder getAmazonDynamoDBClientBuilder() {
return AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1);
}
@Bean
public DynamoDBMapper getDynamoDBMapper(final AmazonDynamoDBClientBuilder builder) {
return new DynamoDBMapper(builder.build());
}
}
Here is your modified BillDAO to make use of injected DynamoDBMapper.
package com.tarkshala;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BillDAO {
private DynamoDBMapper dynamoDBMapper;
@Autowired
public BillDAO(final DynamoDBMapper dynamoDBMapper) {
this.dynamoDBMapper = dynamoDBMapper;
}
public void create(BillDO billDO) {
dynamoDBMapper.save(billDO);
}
}
Since you already added the <context:component-scan base-package="com.tarkshala"/>
in your application context xml, nothing more is required to create beans from ConfigurationAnnotationExample class.
Upvotes: 3