nt的包。 2 使用"Add External JARs"选项添加所需的Spring库,如Spring Hello World示例章节中所述。 3 在com.tutorialspoint包下创建Java类HelloWorld和MainApp。 4 在src文件夹下创建Beans配置文件Beans.xml。 5 最后一步是创建所有Java文件和Bean配置文件的内容,并按以下说明运行应用程序。
以下是HelloWorld.java文件的内容:
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
以下是MainApp.java文件的内容:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("I'm object A");
objA.getMessage();
HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
objB.getMessage();
}
}
以下是singleton作用域所需的Beans.xml配置文件的内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld" scope="singleton">
</bean>
</beans>
当您完成创建源代码和bean配置文件后,让我们运行应用程序。如果您的应用程序一切正常,它将打印以下消息:
Your Message : I'm object A
Your Message : I'm object A
原型作用域(prototype)
如果将作用域设置为prototype,Spring IoC容器将在每次请求特定bean时创建该对象的新bean实例。通常,对于所有有状态的bean,使用prototype作用域,对于无状态的bean,使用singleton作用域。
要定义原型作用域,您可以在bean配置文件中将作用域属性设置为prototype,如下所示:
<!-- 具有prototype作用域的bean定义 -->
<bean id="..." class="..." scope="prototype">
<!-- 此处放置此bean的协作者和配置 -->
</bean>
示例
假设您已经准备好Eclipse IDE,并采取以下步骤创建Spring应用程序:
步骤 描述 1 创建一个名为SpringExample的项目,在创建的项目中的src文件夹下创建一个名为com.tutorialspoint的包。 2 使用"Add External JARs"选项添加所需的Spring库,如Spring Hello World示例章节中所述。 3 在com.tutorialspoint包下创建Java类HelloWorld和MainApp。 4 在src文件夹下创建Beans配置文件Beans.xml。 5 最后一步是创建所有Java文件和Bean配置文件的内容,并按以下说明运行应用程序。
以下是HelloWorld.java文件的内容:
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
以下是MainApp.java文件的内容
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("I'm object A");
objA.getMessage();
HelloWorld objB = (HelloWorld) context.getBean("helloWorl