Spring boot如何注入data类型的数据
sring可以为属性注入基本类型的值,也可以注入一个bean。当想注入非基本类型的值就得用到属性编辑器。它一般用在类型无法识别,如日期等。
实现步骤为以下两步:
继承PropertyEditorSupport
重写其setAsText方法,text是配置文件中的值(也就是为bean注入的值),我们就是将这个text按照需求进行转换
@Configuration
@ConfigurationProperties(prefix = "student")
public class Student {
private Long stuId;// 学号
private Integer age;// 年龄
private Short sex;// 性别 ,0,1,2
private Byte status;// 状态
private Date birthday;// 生日
private String name;// 名字
private Double higth;// 身高
private Float weight;// 体重
private Character genner;// 性别,汉字
//get set 省略
}
@Component
public class DatePropertyEditorSupport extends PropertyEditorSupport {
private String format = "yyyy-MM-dd";
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
this.setValue(sdf.parse(text));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 自定义字符属性编辑器,解决无法注入中文字符的问题
*
* @author zhanghao
* @time 2018年5月21日 下午5:11:35
*/
public class CharPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
this.setValue(Character.valueOf(text.charAt(0)));
}
public String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
}
@SpringBootApplication
@Configuration
public class SpringBootAutoProApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAutoProApplication.class, args);
}
/**
* 添加自定义属性编辑器
*
* @return
*/
@Bean
public CustomEditorConfigurer customEditorConfigurer() {
CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>();
customEditors.put(Date.class, DatePropertyEditorSupport.class);
customEditors.put(Character.class, CharPropertyEditor.class);
customEditorConfigurer.setCustomEditors(customEditors);
return customEditorConfigurer;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootAutoProApplicationTests {
@Autowired
Student student;
@Test
public void contextLoads() {
System.out.println(student);
}
}