Search code examples
javaxmljavabeansapplicationcontext

How to define a bean in ApplicationContext.xml that has no constructor?


I have a class

public class DataStore {
    public String name;
    public String username;
    public String password;
    public String token;
    public String connectionString;
    public String type;
    public String scheme;

    public boolean usesBasicAuth;
    public boolean usesBearerAuth;
}

I need to create an bean for it in another project. But i need to fill the fields somehow. The problem is I can not use <constructor-arg ... /> because there is no constructor.

The code below results in BeanCreationException: "Could not resolve matching constructor"

 <bean id="dataStore"
      class="com.fressnapf.sdk.dataaccess.services.DataStore">
    <constructor-arg index="0" value="${spring.datastore.name}"/>
    ...
</bean>

Solution

  • Assuming, You have public (getters and setters for your) properties, and only the "default (no args) constructor", then You can change your configuration to:

    <bean id="dataStore" class="com.fressnapf.sdk.dataaccess.services.DataStore">
      <property name="connectionString" value="..."/>
      <!-- ... -->
    </bean>
    

    Using property instead of constructor-arg.

    Docs (Spring 4.2): https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html