Spring dependency injection with builder pattern

1.4k Views Asked by At

I have a class A which is going to initialize a new object of class B. This new instance of class B has some DAO. I want to do dependency injection of DAO and provide my custom attributes and build a object and get the result. However, I am getting 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;
    }

}

I am using spring dependency injection to inject just DAO.

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

First, I want to create new object every single time form A thats why I am doing new in class A. Can anyone tell me how to do this in spring? How to use dependency injection with builder pattern for such scenario?

1

There are 1 best solutions below

0
Abhishek Nayak On

I am getting No default constructor found; nested exception is java.lang.NoSuchMethodException

because of a no-arg default constructor not available in B class.

I want to create new object every single time form A thats why I am doing new in class A.

choose prototype bean scope of spring bean scopes.