Reputation: 1064
I need to set a map as a spring bean. I have a map which is intialized in init() method with @PostConstruct keyword.
public class CustomerService
{
@Autowired
TestService testService;
static Map<String, String> someMap;
@PostConstruct
public void initIt() throws Exception {
someMap = new HashMap<String, String>();
someMap = // some code by calling testService
}
@PreDestroy
public void cleanUp() throws Exception {}
}
I call this from applicationContext.xml as a bean.
<bean id="customerService" class="test.com.customer.CustomerService"/>
Initializing the map is working properly, i need to assign the value of this map into bean in order to access the value of the bean in somewhere else in the application.
I found examples of setting up map as a bean, but all were done in XML configurations. How to inject a Map in java springs
How can i achieve this task. Any knowledge is highly appreciated.
Upvotes: 0
Views: 1917
Reputation: 1321
You should just create a getter for that map. And you can @autowire your bean somewhere else and call yourbean.getMap() and you will have it.
In your other class you can:
@Autowired
CustomerService customerService;
And of course greate a getter method in your Customer service for the map. Then in your controller or other service you should autowire your bean with the annotation above. And then use it in your method like that:
Map m = customerService.getMap();
You can create a Flyweight Design Pattern later in your app with that approach(as you are creating a bean to hold a map). Read a tutorial about Flyweight Design Pattern here
Upvotes: 1