简单工厂模式=工厂类+业务类+具体实现类
自我理解:通过类的名字获取工厂中的对象,主要是工厂帮助生成了所需的对象,
示例代码:
工厂类
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class Factory {
//构造方法注入
private final ApplicationContext applicationContext;
/**Spring创建对象时,对象的别名是类名首字母小写 .getSimpleName**/
public Object getBean(String beanId){
if (applicationContext.containsBean(beanId)) {
return applicationContext.getBean(beanId);
}
return null;
}
}
业务类
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private Factory factory;
@GetMapping("/factory")
public String factory(@RequestParam String beanName){
FactoryServiceA serviceA=(FactoryServiceA)factory.getBean(beanName);
return serviceA.factoryServiceA(beanName);
}
具体实现类
@Service("FactoryServiceA")
public class FactoryServiceA {
public String factoryServiceA(String beanName){
System.out.println("---------------AAAAAA----------");
System.out.println(beanName);
return beanName;
}
}
备注:
将工厂类的context注入到容器中去,有多种实现方式
例如:实现ApplicationContextAware接口,将context放到容器中