我试图在我的一个程序中使用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");
}
}我有两个问题:
虽然我将singleton=设置为“false”,但bean只初始化了一次,从输出中可以看出这一点。因此,消息也被设置为对象television1,并且也被反射到电视2中。
我不明白我哪里出了问题。
发布于 2016-12-19 05:40:28
Spring 4仍然支持bean元素上的bean属性,请参阅http://www.springframework.org/schema/beans/spring-beans-4.3.xsd beans模式。
然而,singleton已经消失,这就是为什么您的示例可能失败的原因。它从Spring2.0开始就已经消失了,尽管它在内部仍然支持,以后可能会完全删除。
关于验证器在bean定义上失败的原因:
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"https://stackoverflow.com/questions/41216188
复制相似问题