【问题标题】:How to use Singleton object in Spring?如何在 Spring 中使用 Singleton 对象?
【发布时间】:2014-06-25 09:29:33
【问题描述】:

我是 Spring Framework 的新手。我在 spring 中尝试过以下示例。

@Path("/XZY")
@Service
@Transactional
public class XZY {

    @Autowired
    SampleDAO sampleDao;

    @Autowired
    TestDAO testDao;

     @Autowired
    XZYinterface xzyinterface;

    @POST
    @Produces("text/plain")
    @Path("/checkservice")
    public Response XZYservice(@FormParam("Code") String Code,
            @FormParam("source") String source,
            @FormParam("value") String value)  {
            //return xzyinterface.checkXYZService(Code,sourceName,source); 
        XZYinterface xyz = ServiceFactory.getXZY(999);
        return xyz.checkXYZService(Code,sourceName,source);


    }
}

以下代码将用于创建单例对象

public class Singleton {
        private static sampleA sampleClassA=null;
        private static SampleB sampleClassB=null;
        public static XZYAbstract getXZY(long id){
                if(id == 999){
              if(sampleClass == null){
                sampleClassA = new sampleA();
                }
               return sampleClass;
                     }
                if(id == 9999){
                    sampleClassB = new sampleA();
                }
                return sampleClassB;
        }
}

界面

public interface XZYinterface {
    Response XZYservice(String Code, String source,String value)
}

抽象类和实现接口

public class XZYAbstract implements XZYinterface {
    public XZYAbstract(){
        super();
    }
    @Autowired
    SampleDAO sampleDao;

    @Autowired
    TestDAO testDao;

    public Response checkXYZService(String Code,String source,String value){

    String sample = sampleDao.getValue(code);

    //..source code

    }
}

以下类扩展抽象类。

public class sampleA extends XZYAbstract {

    //some methods.
}

如果我运行应用程序,它会引发以下错误

 SEVERE [com.sun.jersey.spi.container.ContainerResponse] The RuntimeException could not be mapped to a response, re-throwing to the HTTP container: java.lang.NullPointerException
    at com.test.xyz.XZYAbstract.checkXYZService(XZYAbstract.java:112) [:]
    at com.test.XYZ.XZYservice(XZY.java:140) [:]

如果我在没有单例对象的情况下直接调用,则使用自动连接 (//return xzyinterface.checkXYZService(Code,sourceName,source);) 正确初始化值并且它工作正常。 从单例对象抛出,值(sampleDAo,testDao)未正确初始化。

如何解决这个错误?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    原因很简单:这是因为 Spring 只是一个库,而不是对 Java 语言的更改。 Spring 不检测也不增强构造函数,因此获取初始化 Spring bean 的唯一方法是从 Spring 上下文中获取它

    如果你调用new Bean(),你将成为不受Spring影响的Bean实例。

    关于如何使用单例 bean 的问题:什么都不做。 Spring bean 默认是单例的。您可以通过 @org.springframework.beans.factory.config.Scope 注释指定其他范围。参见例如@Scope("prototype") bean scope not creating new bean,它是如何工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      相关资源
      最近更新 更多