gpt4 book ai didi

java - 是否可以让 Spring 忽略不可写或具有无效 setter 方法的 bean 属性

转载 作者:行者123 更新时间:2023-11-29 05:33:07 24 4
gpt4 key购买 nike

有没有办法让 Spring 在下面的情况下不抛出异常?

<bean id="myMain" class="pak.Main">
<property name="name" value="myName"/>
<property name="age" value="100"/>
<property name="human" value="true"/>
</bean>


public class Main {
private String name;
private Integer age;

public void setName(String name) {
this.name = name;
}

public void setAge(Integer age) {
this.age = age;
}

public static void main(String[] args) {
new ClassPathXmlApplicationContext("beans.xml")
.getBean("myMain", Main.class);
}
}

这是抛出的

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myMain' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'human' of bean class [pak.Main]: Bean property 'human' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

最佳答案

想象一下我对答案是肯定的感到惊讶。

输入 InstantiationAwareBeanPostProcessor ...或更具体(更容易实现)InstantiationAwareBeanPostProcessorAdapter .

这个 bean 后处理器在 bean 的属性实例化之前被调用。您可以覆盖以实现您想要做的事情的方法是 postProcessPropertyValues .

此方法提供有关其 bean 及其属性的信息。然后您可以以您认为合适的任何方式修改 bean 的属性。具体来说有一个 PropertyValue.setOptional(boolean)看起来您会感兴趣的方法。

使用您的场景组合一个快速示例,定义一个类:

MyInstantiationAwareBeanPostProcessor.java:

import java.beans.PropertyDescriptor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Component;

@Component
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
if (bean instanceof pak.Main) {
for (PropertyValue pv : pvs.getPropertyValues()) {
if ("human".equals(pv.getName())) {
pv.setOptional(true);
}
}
}
return pvs;
}

}

然后确保以下行在您的上下文中某处:

<bean id="instantiationAwarePP" class="pak.MyInstantiationAwareBeanPostProcessor"/>

而你是金色的。

附言您可能还需要定义 <context:annotation-config />在您的上下文中,以便自动注册后处理器......但我不记得是否有必要。

关于java - 是否可以让 Spring 忽略不可写或具有无效 setter 方法的 bean 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com