Using Enums with map in Spring

If you want to use enums as a key in a map in spring, you can use the following code in your spring.xml:

<bean id="fileCopyService" class="my.package.FileCopyService">
<property name="fileCopier">
<map>
<entry key="IMAGE">
<ref bean="imageFileCopier"/>
</entry>
<entry key="VIDEO">
<ref bean="videoFileCopier"/>
</entry>
<entry key="AUDIO">
<ref bean="audioFileCopier"/>
</entry>
</map>
</property>
</bean>

<bean id="imageFileCopier" class="my.package.ImageFileCopier"/>
<bean id="videoFileCopier" class="my.package.VideoFileCopier"/>
<bean id="audioFileCopier" class="my.package.AudioFileCopier"/>

and your FileCopyService class is as follows:

private Map<ContentType, FileCopier> fileCopier = new HashMap<ContentType, FileCopier>();

and that is all. So you can access a fileCopier withing the code with :

fileCopier.get(getContentType())

no if – else statements, or long switches.

View scope in Spring

If you want to have View Scope in Spring for JSF, firstly read here and here.

The problem with above was, those needed our @Scope(“view”) beans to be serialized.

We didn’t want to serialize our beans so we did the following workaround:

we defined our Autowired DAO classes as :

@Autowired
private transient DAO myDao;

and based on Rick’s above ViewScope implementation we added those 2 lines of code:

public class ViewScope implements Scope, ApplicationContextAware

….

@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}


and finally in get method, after getting the object we did

applicationContext.getAutowireCapableBeanFactory().autowireBean(objToReturn);

to autowire the dependencies again.

hope it helps for you also…