如何在weblogic中实现单例
我尝试实现一个单例类方法,该方法由过滤器类调用。 过滤器类和其余类作为共享库添加到 WLS。
我有两个独立的 Web 应用程序正在运行 - 带过滤器的 servlet - 都在同一台托管服务器上。
所以一切都工作正常,除了单例被实例化两次。 请在代码片段下面找到。
public class Test
{
private static Test ref ;
private DataSource X;
static int Y;
long Z ;
private Test ()
{
// Singleton
Z= 100 ;
}
public static synchronized Test getinstance() throws NamingException, SQLException
{
if(ref == null)
{
ref = new Test() ;
InitialContext ic = new InitialContext();
ref.X = (DataSource)ic.lookup ("jdbc/Views");
}
return ref ;
}
public Object clone()throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
public int sampleMethod (int X) throws SQLException
{
}
}
过滤方法:
public final class Filter implements Filter
{
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
{
try
{
Test ref = Test.getinstance();
log.logNow(ref.toString());
.......
}
}
}
在日志中我得到两个不同的引用 - 比如说
Test@f1a2e06 Test@f180f10
我在这里做错了什么吗?任何帮助都会很棒。
I tried implementing a singleton class method , which is invoked by a filter class.
The filter class and the rest of the classes , are added to WLS as a shared library.
And i have two separate web apps running - servlets with filter - both on the same managed server.
So everything is working fine except , the singleton is getting instantiated twice .
plz find below the code snippet.
public class Test
{
private static Test ref ;
private DataSource X;
static int Y;
long Z ;
private Test ()
{
// Singleton
Z= 100 ;
}
public static synchronized Test getinstance() throws NamingException, SQLException
{
if(ref == null)
{
ref = new Test() ;
InitialContext ic = new InitialContext();
ref.X = (DataSource)ic.lookup ("jdbc/Views");
}
return ref ;
}
public Object clone()throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
public int sampleMethod (int X) throws SQLException
{
}
}
Filter method:
public final class Filter implements Filter
{
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
{
try
{
Test ref = Test.getinstance();
log.logNow(ref.toString());
.......
}
}
}
In the log am getting two different references - say
Test@f1a2e06 Test@f180f10
Am i doing something wrong here ? Any help would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Servlet 容器针对不同的应用程序使用不同的类加载器。所以我不相信可以共享实例。您可以做的也许是通过 JNDI 注册实例。
A servlet container uses different classloaders for different application. So I don't believe it is possible to share an instance. What you can do is perhaps register the instance via JNDI.