使用 spring 的类在创建的时候,父类有没什么好办法获取到子类传进来的信息?

2018-01-06 08:28:46 +08:00
 lhx2008
如果是传统的话可以用带参数的构造函数,但是 spring 中有什么好方法?
我目前只能用 e.printstacktrace 的黑科技,但是代码总感觉怪怪的。
2893 次点击
所在节点    Java
9 条回复
jatesun
2018-01-06 08:35:35 +08:00
觉得还是从设计角度找找问题吧
lhx2008
2018-01-06 08:38:56 +08:00
@jatesun 主要是有个 BaseService 的需求,不同的 Service 在创建的时候自动指派 dao,所以 BaseService 必须要知道是哪个子 service 才能给他分配
jatesun
2018-01-06 08:44:17 +08:00
@lhx2008 那为什么不直接在子类自动注入 dao 呢?用 @Autowired 就行吧
lhx2008
2018-01-06 08:53:23 +08:00
@jatesun 但是如果不只要 dao 的话,看起来还是挺臃肿的
jatesun
2018-01-06 08:55:58 +08:00
@lhx2008 为了简洁丢了可读性,我觉得就像丢了西瓜捡了芝麻
Charkey
2018-01-06 11:05:03 +08:00
public class BaseServiceImpl {
private BaseRepository<E, K> baseRepository;
public BaseServiceImpl(BaseRepository<? super E, ? super K> baseRepository) {
this.baseRepository =(BaseRepository<E, K>)baseRepository;
}
}

public class CustOrderServiceImpl {
CustOrderRepository custOrderRepository;
@Autowired
public CustOrderServiceImpl(CustOrderRepository custOrderRepository) {
super(custOrderRepository);
this.custOrderRepository = custOrderRepository;
}
}

粗略的代码,大概这样?
GoodRainChen
2018-01-06 17:39:18 +08:00
可以用模板方法模式
sunsulei
2018-01-06 22:36:26 +08:00
看一下通用 mapper 我感觉他推荐的泛型注入的方式就是你想要的。
grq100296
2018-01-12 17:26:12 +08:00
泛型应该可以吧,类似 mybaties plus 里提供的 IService

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/420506

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX