项目结构图
代码
HelloWorld.java
package org.spring.model;
public class HelloWorld {
public String sayHello(){
return "hello world";
}
}
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.xsd">
<bean id="helloWorld" class="org.spring.model.HelloWorld" scope="prototype"/>
</beans>
Test.java
package org.spring.test;
import org.spring.model.HelloWorld;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
//创建spring的工厂
private BeanFactory factory=new ClassPathXmlApplicationContext("xml/beans.xml");
@org.junit.Test
public void testHello() {
//通过工厂获取对象(下面getBean方法中的参数是beans.xml文件中bean的id)
//HelloWorld hello=(HelloWorld) factory.getBean("helloWorld"); //不指定返回对象的类型(默认返回object类型,需要进行强制转换)
HelloWorld hello=factory.getBean("helloWorld", HelloWorld.class); //返回指定类型的对象
System.out.println(hello.sayHello());
HelloWorld hello2=factory.getBean("helloWorld", HelloWorld.class);
System.out.println(hello==hello2); //如果在bean中没有配置scope,默认是singleton(单独,单例),返回true,当把bean中的scope设置为prototype(原型,多例)时返回false
}
}