`
tooby
  • 浏览: 110683 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

在Tomcat的多个WAR之间共享Spring

 
阅读更多

在tomcat内共享Spring context。

 

    <Resource auth="Container" 
       contextConfigLocation
="/com/test/application-context.xml" 
       factory
="com.test.TomcatWebApplicationContextResourceFactory" 
       name
="bean/RootApplicationContextFactory" 
       type
="org.springframework.context.ApplicationContext"/>

 

上面这段配置的意思就是,当有人通过jndi名称”bean/RootApplicationContextFactory”来查找对象时,容器就新建一个TomcatWebApplicationContextResourceFactory类实例,并调用它的getObjectInstance方法来获得资源对象。这个工厂类要是想javax.naming.spi.ObjectFactory接口。代码如下:

 

package com.test;

 

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TomcatWebApplicationContextResourceFactory implements
        ObjectFactory {
    
private static final String PARAM = "contextConfigLocation";
        
private static final String DEFAULT = "application-context.xml";

    private static ApplicationContext context; //被共享的spring上下文

    
private void init(String confFile) {
        context 
= new ClassPathXmlApplicationContext(confFile);
    }

    public Object getObjectInstance(Object obj, 
                        Name name, Context nameCtx,
            Hashtable
<??> environment) throws Exception {
        
if (null == context) {
            
// Customize the bean properties from our attributes
            Reference ref = (Reference) obj;

                        //从xml配置文件里取得contextConfigLocation元素的值
            RefAddr addr = ref.get(PARAM); 

            if (null != addr) {
                String value 
= (String) addr.getContent();
                init(value);
            } 
else {
                init(DEFAULT);
            }
        }
        
return context;
    }
}

 

1.2 在web应用中引用上面定义的资源
修改tomcat/conf/web.xml,添加以下的内容,这样在这个tomcat下的所有的web应用就都可以访问共享的spring上下文了。

    <resource-env-ref>
        
<description>Object factory for Root applicationcontext</description>
        
<resource-env-ref-name> bean/RootApplicationContextFactory 
        
</resource-env-ref-name>
        
<resource-env-ref-type> org.springframework.context.ApplicationContext 
        
</resource-env-ref-type>
    
</resource-env-ref>

 

1.3 加入依赖的包
从第一步可以看出,tomcat容器需要访问spring的一些类,需要初始化上下文,所以要把初始化上下文时用到的类共享给tomcat。最简单的方法是把所有相关的类和jar包复制到tomcat/lib目录。还可以修改catalina.properties实现,如下:

 

shared.loader=/usr/local/jars/*.jar

 

上面的代码让tomcat载入自定目录里面所有的jar文件。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics