【问题标题】:Spring dependency injection with builder pattern使用构建器模式的 Spring 依赖注入
【发布时间】:2015-04-04 01:10:46
【问题描述】:

我有一个 A 类,它将初始化 B 类的一个新对象。B 类的这个新实例有一些 DAO。我想做 DAO 的依赖注入并提供我的自定义属性并构建一个对象并获得结果。但是,我收到了No default constructor found; nested exception is java.lang.NoSuchMethodException

public class A {

    public void setChildren() {
        B b = new B.Builder().children(3).build();
    }

}

class B {

    private PersonDAO personDAO;
    private final int children;

    private B(Builder buil) {
        this.children = buil.children;
    }

    public static class Builder {

        private int children;

        public Builder children(int ch) {
            this.children = ch;
            return this;
        }

        public Builder build() {
            return new B(this);
        }

    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

}

我正在使用 spring 依赖注入来注入 DAO。

<bean id="b" class="com.company.B">
    <property name="personDAO" ref="personDAO"/>
</bean> 

首先,我想每次从 A 中创建一个新对象,这就是为什么我在 A 类做 new 的原因。谁能告诉我在春天怎么做?在这种情况下如何使用依赖注入和构建器模式?

【问题讨论】:

    标签: java spring builder


    【解决方案1】:

    我得到没有找到默认构造函数;嵌套异常是 java.lang.NoSuchMethodException

    因为 B 类中没有无参数默认构造函数。

    我想每次从 A 中创建一个新对象,这就是我的原因 在A班做新的。

    选择springbean scopes的prototype bean范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多