Spring Boot中注解使用工厂模式
Spring Boot中注解使用工厂模式
本文详细介绍如何在Spring Boot中使用注解的方式实现工厂模式。主要解决了如何注入工厂提供的实例的问题。
问题
在controller层中注入工厂提供的service时,需要先注入工厂,再利用工厂注入工厂提供的service实例。代码如下:
public class MyController{ @Autowired StudentServiceFactory factory; StudentService service = factory.obtainStudentService("HustStudentServiceImpl"); }
此时会报空指针异常。
原因
Spring赋值注入是在类实例化之后完成,即先调用构造方法完成类实例化,再进行值注入。也就是说在初始化service时还未注入factory,自然会报空指针异常。
解决办法
1. 不使用@AutoWired注解,new一个factory
StudentServiceFactory facatory = new StudentServiceFactory();
但是这很不Spring,而且也不符合工厂模式规范(工厂模式应该是单例,因为一个工厂就够了),还需要额外实现单例模式。
2. 使用@PostConstruct注解
被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法执行执行之后执行。 事实上,这个注解可以使用在任何类上。改写后的代码如下:
public class MyController { @Autowired StudentServiceFactory factory; StudentService service; @PostConstruct public void init() { service = factory.obtainStudentService("hustStudentServiceImpl"); }
问题得到解决。
总结
主要学习了@PostConstruct注解的使用。
下一篇:
KMP java代码的简单实现