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")
5. applicationContext.xml (singleton="true")
6. singleton="false" 运行结果
7. singleton="true" 运行结果
8. 小结:
通过以上分析可以得出结论:在spring的bean配置中,若singleton=“false”,则该bean为非单例,即每请求一次,就会重新创建一个;若singleton=“true”则结论相反。
补充:默认情况下,singleton=“true”.