xinyb
2024-08-30 f5cc47742dd3d2f2ffd8443ffc82a912683f7824
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.yc.factory;
 
import java.sql.SQLException;
 
import org.springframework.web.context.WebApplicationContext;
 
import com.yc.multiData.MultiDataSource;
/**
 * 取得spring管理的bean实例
 * @author 邓文峰
 * 2010-2-24
 * */
public class FactoryBean{
    
    private static WebApplicationContext wctx;
    public static WebApplicationContext getCtx() {
        return wctx;
    }
    public static void setCtx(WebApplicationContext ctx) {
        wctx = ctx;
        MultiDataSource multiDataSource=(MultiDataSource)wctx.getBean("multiDataSource");
        try {
            multiDataSource.refreshDataSource(null);
        } catch (SQLException e) {
            System.out.println(e.getMessage()+"[连接不到数据库,请检查数据源配置]");
            e.printStackTrace();
        }
        //ctx.getServletContext().getContext("/").getContext("/").getContextPath();
    }
    
    public static Object getBean(String beanName){
        return wctx.getBean(beanName);
    }
 
    /**
     * 通过类的class从IOC容器取得对象实例
     * AttachmentAction attachmentAction = FactoryBean.getBean(AttachmentAction.class);
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType){
        return wctx.getBean(requiredType);
    }
}