java单例模式和spring多例模式的问题

u010764741 2016-07-08 11:19:38
今天看书的时候发现一个问题,TestSingelIoc这个类我java代码用的单例模式写的,在spring中配置scope="prototype",然后把它注入到其他类中输出,为什么输出的东西不一样?搞不明白。。。大家看看代码吧
public class TestSingelIoc {
private static final TestSingelIoc singelIoc=new TestSingelIoc();
private TestSingelIoc(){
}
public static TestSingelIoc getSingelIoc(){
return singelIoc;
}
}
public class Test {
private TestSingelIoc singelIoc;
public Test(TestSingelIoc singelIoc){
this.singelIoc=singelIoc;
}
public void initmethod(){
System.out.println(singelIoc);
}
}
public class TestIoc {
private TestSingelIoc singelIoc;
public TestIoc(TestSingelIoc singelIoc){
this.singelIoc=singelIoc;
}
public void initmethod(){
System.out.println(singelIoc);
}
}
spring:
<bean id="testIoc" class="com.spring.ioc.TestIoc" init-method="initmethod">
<constructor-arg name="singelIoc" ref="testSingelIoc"></constructor-arg>
</bean>
<bean id="test" class="com..spring.ioc.Test" init-method="initmethod">
<constructor-arg name="singelIoc" ref="testSingelIoc"></constructor-arg>
</bean>
<bean id="testSingelIoc" class="com.spring.ioc.TestSingelIoc" init-method="getSingelIoc" scope="prototype">
</bean>

输出:com.spring.ioc.TestSingelIoc@11bf74e
com.spring.ioc.TestSingelIoc@1708205
...全文
316 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010764741 2016-07-08
  • 打赏
  • 举报
回复
qq_15915835 2016-07-08
  • 打赏
  • 举报
回复
spring创建bean用的是反射,单例并没有什么卵用。
u010764741 2016-07-08
  • 打赏
  • 举报
回复
我发现是我写错了,factory-method写成了init-method了。不过这样一来我解决了两个问题:一个是private的构造方法也可以被spring实例化,一个是单例的时候确实spring指定为多例也是同一个对象的。。。。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧