首页 > 解决方案 > 我们应该将每个对象都暴露为 spring bean 吗?

问题描述

class TibcoPasswordRetriever {

    private TibcoPasswordUtil tibcoPasswordUtil;

    public TibcoPasswordRetriever(TibcoPasswordUtil tibcoPasswordUtil) {
        this.tibcoPasswordUtil = tibcoPasswordUtil;
    }

}

class TibcoPasswordRetriever {

    private TibcoPasswordUtil tibcoPasswordUtil;

    public TibcoPasswordRetriever() {
        this.tibcoPasswordUtil = new TibcoPasswordUtil();
    }

}

这是 TibcoPasswordRetriever 的两个定义。

问题:我只在 TibcoPasswordRetriever 类中使用 TibcoPasswordUtil。依赖注入仍然是个好主意吗?

进一步的问题:我们是否应该将每个可能的对象都创建为spring bean(只是因为可以这样做)

标签: javaspringdependency-injection

解决方案


Question : I am using TibcoPasswordUtil in TibcoPasswordRetriever class only. Is dependency injection still a good idea?

Probably dependency injection is good idea if TibcoPasswordUtil is a Singletone. You did not provide TibcoPasswordUtil class in the question. Addind Util to name does not mean many here. Consider writing more about architecture and context.

Further question: Should we create expose every possible object as spring bean (just because it is possible to do that)

No it is not, cause better solution would be not to be dependent so much on framework. Ask yourself questions like:

If you don't have to, then why is the advantage of it?

Why is the benefit of not doing so?

Like i wrote above less coupled code is better. In the future it would be easier to for example change framework.


推荐阅读