前言
在应用spring的过程中,咱们有没有发现它的扩大能力很强呢? 因为这个劣势的存在,使得spring具备很强的包容性,所以很多第三方利用或者框架能够很容易的投入到spring的怀抱中。明天咱们次要来学习Spring中很罕用的11个扩大点,你用过几个呢?
- 类型转换器
如果接口中接管参数的实体对象中,有一个字段类型为Date,但理论传递的参数是字符串类型:2022-12-15 10:20:15,该如何解决?
Spring提供了一个扩大点,类型转换器Type Converter,具体分为3类:
Converter<S,T>: 将类型 S 的对象转换为类型 T 的对象
ConverterFactory<S, R>: 将 S 类型对象转换为 R 类型或其子类对象
GenericConverter:它反对多种源和指标类型的转换,还提供了源和指标类型的上下文。 此上下文容许您依据正文或属性信息执行类型转换。
还是不明确的话,咱们举个例子吧。
定义一个用户对象
@Data
public class User {
private Long id;private String name;private Date registerDate;
}
复制代码
实现Converter接口
public class DateConverter implements Converter<String, Date> {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@Overridepublic Date convert(String source) { if (source != null && !"".equals(source)) { try { simpleDateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } } return null;}
}
复制代码
将新定义的类型转换器注入到Spring容器中
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Overridepublic void addFormatters(FormatterRegistry registry) { registry.addConverter(new DateConverter());}
}
复制代码
调用接口测试
@RequestMapping("/user")
@RestControllerpublic class UserController { @RequestMapping("/save") public String save(@RequestBody User user) { return "success"; }}
复制代码
申请接口时,前端传入的日期字符串,会主动转换成Date类型。
获取容器Bean
在咱们日常开发中,常常须要从Spring容器中获取bean,然而你晓得如何获取Spring容器对象吗?
2.1 BeanFactoryAware
@Service
public class PersonService implements BeanFactoryAware {
private BeanFactory beanFactory;@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {this.beanFactory = beanFactory;
}
public void add() {
Person person = (Person) beanFactory.getBean("person");
}
}
复制代码
实现BeanFactoryAware接口,而后重写setBeanFactory办法,能够从办法中获取spring容器对象。
2.2 ApplicationContextAware
@Service
public class PersonService2 implements ApplicationContextAware {
private ApplicationContext applicationContext;@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;
}
public void add() {
Person person = (Person) applicationContext.getBean("person");
}
}
复制代码
实现ApplicationContextAware接口,而后重写setApplicationContext办法,也能够通过该办法获取spring容器对象。
2.3 ApplicationListener
@Service
public class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {applicationContext = event.getApplicationContext();
}
public void add() {
Person person = (Person) applicationContext.getBean("person");
}
}
复制代码全局异样解决
以往咱们在开发界面的时候,如果出现异常,要给用户更敌对的提醒,例如:
@RequestMapping("/test")
@RestController
public class TestController {@GetMapping("/add")
public String add() {int a = 10 / 0; return "su";
}
}