V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lhx2008
V2EX  ›  Java

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

  •  
  •   lhx2008 ·
    xenv · 2018-01-06 08:28:46 +08:00 · 2835 次点击
    这是一个创建于 2273 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如果是传统的话可以用带参数的构造函数,但是 spring 中有什么好方法?
    我目前只能用 e.printstacktrace 的黑科技,但是代码总感觉怪怪的。
    9 条回复    2018-01-12 17:26:12 +08:00
    jatesun
        1
    jatesun  
       2018-01-06 08:35:35 +08:00
    觉得还是从设计角度找找问题吧
    lhx2008
        2
    lhx2008  
    OP
       2018-01-06 08:38:56 +08:00 via Android
    @jatesun 主要是有个 BaseService 的需求,不同的 Service 在创建的时候自动指派 dao,所以 BaseService 必须要知道是哪个子 service 才能给他分配
    jatesun
        3
    jatesun  
       2018-01-06 08:44:17 +08:00
    @lhx2008 那为什么不直接在子类自动注入 dao 呢?用 @Autowired 就行吧
    lhx2008
        4
    lhx2008  
    OP
       2018-01-06 08:53:23 +08:00
    @jatesun 但是如果不只要 dao 的话,看起来还是挺臃肿的
    jatesun
        5
    jatesun  
       2018-01-06 08:55:58 +08:00
    @lhx2008 为了简洁丢了可读性,我觉得就像丢了西瓜捡了芝麻
    Charkey
        6
    Charkey  
       2018-01-06 11:05:03 +08:00   ❤️ 1
    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
        7
    GoodRainChen  
       2018-01-06 17:39:18 +08:00
    可以用模板方法模式
    sunsulei
        8
    sunsulei  
       2018-01-06 22:36:26 +08:00 via iPhone
    看一下通用 mapper 我感觉他推荐的泛型注入的方式就是你想要的。
    grq100296
        9
    grq100296  
       2018-01-12 17:26:12 +08:00
    泛型应该可以吧,类似 mybaties plus 里提供的 IService
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2981 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.