spring中bean的singleton属性

    1.  UserDao.java
package com.lxh.springSingleton;

public interface UserDao {
	// 保存User
	public void save();
}
    2.  UserDaoImpl.java
package com.lxh.springSingleton;

public class UserDaoImpl implements UserDao {

	@Override
	public void save() {
		System.out.println("save user ...");
	}

}
    3.  UserService.java
package com.lxh.springSingleton;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserService {
	// ApplicationContext
	public static ApplicationContext context = new ClassPathXmlApplicationContext(
			UserService.class.getResource("").toString()
					+ "/applicationContext.xml");
	// 日志
	private static Logger logger = Logger.getLogger(UserService.class);
	// 属性
	private UserDao userDaoImpl;

	// set,get
	public UserDao getUserDaoImpl() {
		return userDaoImpl;
	}

	public void setUserDaoImpl(UserDao userDaoImpl) {
		this.userDaoImpl = userDaoImpl;
	}

	// userService
	public static void main(String[] args) {
		System.out.println();
		UserService us = (UserService) context.getBean("userService");
		UserService us2 = (UserService) context.getBean("userService");
		
		logger.info("*****"+us +","+us2+"*****");
		logger.info("*****"+us.userDaoImpl+","+us2.userDaoImpl+"*****");
	
	}
}
    4.  applicationContext.xml (singleton="false")
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="userDao" class="com.lxh.springSingleton.UserDaoImpl" singleton="false"/>
	<bean id="userService" class="com.lxh.springSingleton.UserService" singleton="false">
		<property name="userDaoImpl" ref="userDao"/>
	</bean>
</beans>
    5.  applicationContext.xml (singleton="true")
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="userDao" class="com.lxh.springSingleton.UserDaoImpl" singleton="true"/>
	<bean id="userService" class="com.lxh.springSingleton.UserService" singleton="true">
		<property name="userDaoImpl" ref="userDao"/>
	</bean>
</beans>
    6.  singleton="false" 运行结果

    7.  singleton="true"  运行结果

    8.  小结:

        通过以上分析可以得出结论:在spring的bean配置中,若singleton=“false”,则该bean为非单例,即每请求一次,就会重新创建一个;若singleton=“true”则结论相反。

        补充:默认情况下,singleton=“true”.




转载于:https://my.oschina.net/u/1989867/blog/531541

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值