Spring MVC automatically injects enumerated types into objects
- 2020-07-21 08:11:41
- OfStack
spring MVC cannot be injected directly if there is an enumerated type in an object, because it only implements automatic conversion injection of 1 basic data type, but it also provides an extensible interface that can be extended according to your needs. Here is an example:
First: This is an enumeration class:
/**
* News category
* @author: ShangJianguo
* 2014-6-11 In the morning 10:51:07
*/
public enum ENews {
company("0"), // Corporate news
industry("1");// Industry news
private final String value;
private ENews(String v) {
this.value = v;
}
public String toString() {
return this.value;
}
public static ENews get(int v) {
String str = String.valueOf(v);
return get(str);
}
public static ENews get(String str) {
for (ENews e : values()) {
if(e.toString().equals(str)) {
return e;
}
}
return null;
}
}
The following is an entity class:
public class News {
private ENews type;
private String adminuid;
private String title;
private String summary;
private String author;
private String origin;
private String originurl;
private String content;
// omit setter and getter methods
}
Here is the controller layer:
@RequestMapping(value="/news/update", method=RequestMethod.POST)
@ResponseBody
public boolean edit_update(Map<String, Object> model,HttpServletRequest request,News news){
String adminid = getAdminid();
news.init(adminSO.getAdminByAdminid(adminid).getUid());
if (news != null) {
if (newsSO.update(news)) {
return true;
}
}
return false;
}
However, at this point the program is not able to run properly, the real point is the following, write an enumerated transformation class (Converter) :
public class StringToENewsConverter implements Converter<String, ENews>{
/* (non-Javadoc)
* @see com.fasterxml.jackson.databind.util.Converter#convert(java.lang.Object)
* @author: ShangJianguo
* 2014-6-12 In the afternoon 4:56:30
*/
@Override
public ENews convert(String source) {
String value = source.trim();
if ("".equals(value)) {
return null;
}
return ENews.get(Integer.parseInt(source));
}
}
Then configure in the configuration file for spring mvc:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.ngenius.core.converters.StringToENewsConverter" />
</set>
</property>
</bean>
In this way, spring can run when injecting the fields of the object, directly converting the content received from the front end to ENews type for encapsulation.