Does Spring require all beans to have a default constructor?

后端 未结 3 1582
旧时难觅i
旧时难觅i 2020-12-06 09:09

I don\'t want to create a default constructor for my auditRecord class.

But Spring seems to insist on it:

org.springframework.beans.fact         


        
相关标签:
3条回答
  • 2020-12-06 09:53

    nicholas' answer is right on the money for XML configuration. I'd just like to point out that when using annotations to configure your beans, it's not only simpler to do constructor injection, it's a much more natural way to do it:

    class Foo {
        private SomeDependency someDependency;
        private OtherDependency otherDependency;
    
        @Autowired
        public Foo(SomeDependency someDependency, OtherDependency otherDependency) {
            this.someDependency = someDependency;
            this.otherDependency = otherDependency;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:54

    You might be able to do constructor based injection, i.e. something like this (taken from documentation found here)

    <bean id="foo" class="x.y.Foo">
        <constructor-arg ref="bar"/>
        <constructor-arg ref="baz"/>
    </bean>
    

    but I'm not sure it will work.

    If you are defining a JavaBean, you need to follow the convention and put a public no-arg constructor on it.

    0 讨论(0)
  • 2020-12-06 10:03

    No, you are not required to use default (no arg) constructors.

    How did you define your bean? It sounds like you may have told Spring to instantiate your bean something like one of these:

    <bean id="AuditRecord" class="com.bartholem.AuditRecord"/>
    
    <bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
      <property name="someProperty" val="someVal"/>
    </bean>
    

    Where you did not provide a constructor argument. The previous will use default (or no arg) constructors. If you want to use a constructor that takes in arguments, you need to specify them with the constructor-arg element like so:

    <bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
      <constructor-arg val="someVal"/>
    </bean>
    

    If you want to reference another bean in your application context, you can do it using the ref attribute of the constructor-arg element rather than the val attribute.

    <bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
      <constructor-arg ref="AnotherBean"/>
    </bean>
    
    <bean id="AnotherBean" class="some.other.Class" />
    
    0 讨论(0)
提交回复
热议问题