我试图在我的一个程序中使用 Spring 4 的 bean 范围作为原型(prototype),以检查是否根据请求创建了不同的对象。为此,我使用了以下代码片段:
<bean id="television" class = "org.java.springcore.Television" scope="prototype">
<property name="model" value="Samsung_6970"/>
<property name="yearOfManufature" value="2016"/>
<property name="diameter" value="55"/>
</bean>
然后我在主类中初始化三角形对象如下:
public class TelevisionUser {
/**
* @param args
*/
public static void main(String[] args) {
// BeanFactory factory = new XmlBeanFactory(new
// FileSystemResource("spring.xml"));
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();
Television television1 = (Television) context.getBean("television");
television1.setMsg("Setting messege for Television");
System.out.println("The message for television 1 is: "+television1.getMsg());
Television television2 = (Television) context.getBean("television");
System.out.println("The message for television 2 is: "+television2.getMsg());
}
}
我的电视课如下:
public class Television implements InitializingBean
{
private Integer yearOfManufature;
private String model;
private Integer diameter;
private String msg;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Integer getYearOfManufature() {
return yearOfManufature;
}
public void setYearOfManufature(Integer yearOfManufature) {
this.yearOfManufature = yearOfManufature;
}
public Integer getDiameter() {
return diameter;
}
public void setDiameter(Integer diameter) {
this.diameter = diameter;
}
/**
* @return the msg
*/
public String getMsg() {
return msg;
}
/**
* @param msg the msg to set
*/
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Initialising the Bean Television");
}
}
我有两个问题:
当我使用范围属性时,XML validator 抛出错误,“必须为元素类型“bean”声明属性“范围”。” Spring 4 不再使用 scope 属性了吗?
如果我使用属性 singleton 并将其值设置为 false,那么我的程序会表现异常。即输出将变为:
初始化 Bean Television 电视 1 的消息是:电视设置消息 电视 2 的消息是:设置电视的消息
bean 仅被初始化一次,从输出中可以明显看出,即使我设置了 singleton="false"。因此,消息也正在为对象 television1 设置,并且也正在为 television 2 反射(reflect)。
我不明白我哪里错了。
最佳答案
bean
元素的
scope
属性在 Spring 4 中仍然受支持,参见 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd bean 架构。
singleton
消失了,这就是您的示例可能失败的原因。它从 Spring 2.0 开始就消失了,但仍然在内部得到支持,并且可能会在以后完全删除。
关于为什么 validator 在你的 bean 定义上失败:
检查您是否有正确的架构位置:
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
我在您的示例中看到一些双空格,请检查是否只有空格或制表符并且没有来自 Unicode 的奇怪字符。
关于java - Spring 4 不支持 scope 属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41216188/