考慮以下配置@Scope(「原型」)不能正常工作
public class MainApp {
public static void main(String args[]){
ApplicationContext ac=new ClassPathXmlApplicationContext("src/Beans.xml");
HelloWorld obj1=(HelloWorld) ac.getBean("helloWorld");
obj1.setMessage("OBJ1");
HelloWorld obj2=(HelloWorld) ac.getBean("helloWorld");
//obj2.setMessage("OBJ2");
System.out.println(obj1.getMessage());
System.out.println(obj2.getMessage());
}
}
@Scope("prototype")
public class HelloWorld {
String message;
public String getMessage() {
return "Your Message:"+message;
}
public void setMessage(String message) {
this.message = message;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="SpringDemo.src" />
<bean id="helloWorld" class="src.HelloWorld">
</bean>
</beans>
如果我沒看錯的是呈現出辛格爾頓範圍的行爲。有人能讓我知道爲什麼它不像「原型」範圍那樣行事嗎?
class name'src.HelloWorld' is wrong。您不需要將'src'目錄指定爲'package' –
如果我刪除它,它將顯示錯誤無法在類路徑資源[src/Beans.xml]中定義名稱爲'helloWorld'的bean的類[HelloWorld] ;我得到的輸出,但它的單身作用域,而不是原型 – Aashish
@Aashish你看到的行爲究竟是什麼? – soulcheck