通过配置文件中对象标签的 scope 属性
设置为 singleton 为单例对象,默认为单例
设置为 prototype 为非单例对象
例:
配置文件
<?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="user" class="org.example.entiy.User">
<property name="age" value="18"></property>
<property name="sex" value="男"></property>
</bean>
<!--设置为非单例对象 -->
<bean id="user02" class="org.example.entiy.User" scope="singleton">
<property name="age" value="18"></property>
<property name="sex" value="男"></property>
</bean>
</beans>
代码测试
@Test
public void shouldAnswerWithTrue(){
// 加载Spring配置文件
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("Spring001.xml");
// 通过Spring创建User对象
User user01=(User)app.getBean("user");
User user02=(User)app.getBean("user");
// 非单例对象
User user001=(User)app.getBean("user02");
User user002=(User)app.getBean("user02");
System.out.println(user01==user02); //true
System.out.println(user001==user002); //false
}