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