【发布时间】:2014-06-20 00:44:38
【问题描述】:
我最近开始学习 Spring。由于我是 Spring 新手,我想到了几个问题。其中之一是:
如此处所述“一旦容器加载了 spring 配置,所有 bean 都会被实例化。org.springframework.context.ApplicationContext 容器遵循预加载方法。” LINK
1 - 这是否意味着使用 Spring ApplicationContext 创建的所有对象都是单例?
我创建了这个简单的测试
@Component
public class HelloService {
private ApplicationContext context;
public HelloService() {
}
@Autowired
public HelloService(ApplicationContext context) {
this.context = context;
}
public String sayHello() {
return "Hi";
}
}
public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
}
});
HelloService helloService1 = context.getBean(HelloService.class);
System.out.println(helloService1);
HelloService helloService2 = context.getBean(HelloService.class);
System.out.println(helloService2);
HelloService helloService3 = injector.getInstance(HelloService.class);
System.out.println(helloService3);
HelloService helloService4 = injector.getInstance(HelloService.class);
System.out.println(helloService4);
}
}
输出是
foo.bar.HelloService@191e8b08 // same instance
foo.bar.HelloService@191e8b08 // same instance
foo.bar.HelloService@6ba67ab5 // different instance
foo.bar.HelloService@7ec23849 // different instance
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="foo.bar"/>
</beans> // this is mu config bean.
在 Guice 中,您必须明确表示您希望将此对象实例化为单例。
2- 当 Spring 创建保持某种状态的对象时,这不会产生一些问题吗?
3- 如何告诉 Spring 创建一个新对象?
【问题讨论】:
-
让我们看看你的配置。 Spring bean 默认是单例的。
-
也需要
HelloService类。
标签: java spring dependency-injection guice