如何在ApplicationContext.xml中定义一个没有构造函数的bean



我有一个类

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;
}

我需要在另一个项目中为它创建一个bean。但我需要以某种方式填补空白。问题是我不能使用<constructor-arg ... />,因为没有构造函数。

以下代码导致BeanCreationException:"无法解析匹配的构造函数">

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

假设您有公共(getter和setter用于您的(属性,并且只有"默认(无args(构造函数",那么您可以将配置更改为:

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

使用CCD_ 2而不是CCD_。

文档(春季4.2(:https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html

是的,有一个构造函数。

如果您没有显式地放置一个,Java将自动添加一个默认(非参数(构造函数。

用那个。它会将所有实例变量设置为其类型的默认值。

在您的情况下:每个String变量为null,每个布尔值为false。

相关内容

最新更新