`
sw1982
  • 浏览: 503579 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Spring-搞定bean加载

阅读更多

spring的IOC灰常的强大。。特别是管理Web项目中的自动加载。

但是实际应用中,可能会碰到这样两类的问题:

1.写UnitTest的时候,需要脱离容器,手动读取xml文件加载bean。

2.在一个Web容器中,可能某个脱离了spring管理(也就是一个非bean)的类,需要感知并读取某个spring容易的bean。

 

下面转了2篇文章,分别是对应上面2个问题的解决方案。

 

 

壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹壹

 

http://hi.baidu.com/%C9%CF%B5%DB%D2%B2%B7%B8%C0%A7/blog/item/f934474a104c3e2008f7ef66.html

Spring中读取bean配置文件的几种方式     CSDN Blog推出文章指数概念,文章指数是对Blog文章综合评分后推算出的,综合评分项分别是该文章的点击量,回复次数,被网摘收录数量,文章长度和文章类型;满分100,每月更新一次.

BeanFactory允许InputStream作为构造函数的参数,也可以org.springframework.core.io.Resource接口。下面这个例子是用ClassPathResource作为参数:

Resource resource = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resource);
ActionBean action = (ActionBean) factory.getBean("actionBean");

如果同一个Bean在配置文件有多个bean的定义,则用下面的方法取得所有的对象:
Resource resource = new ClassPathResource("bean.xml");
ListableBeanFactory factory = new XmlBeanFactory(resource);
       
Map helloBeans = factory.getBeansOfType(ActionBean.class, false, false);

    一个应用程序中往往有很多的Bean要放在配置文件,如果所有的Bean都放在一个文件中,维护起来就相当的麻烦,这时我们可以按照模块把每个模块用到Bean放到不同的配置文件,Spring提供了相应的方法:
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(reg);
   
// 載入bean定義檔   
reader.loadBeanDefinitions(new ClassPathResource("bean1.xml"));
reader.loadBeanDefinitions(new ClassPathResource("bean2.xml"));
....

// 取得Bean
BeanFactory bf = (BeanFactory) reg;
Object o = bf.getBean("actionBean");

===================================================================

在读spring in aciton 时,他用的BeanFactory factory = new XmlBeanFactory(new FileInputStream("hello.xml"));
可是现在的用的1.2.6版本的构造器(XmlBeanFactory)只能接收Resource接口了,所以调不出来是正常的事情,假设现在有一个文件hello.xml
读取方法

1:ApplicationContext cx=new FileSystemXmlApplicationContext("hello.xml");//指定的路径去找文件
2:ApplicationContext factory = new ClassPathXmlApplicationContext("hello.xml");//还会在classpath去找
3:Resource fa = new FileSystemResource("hello.xml");
BeanFactory factory=new XmlBeanFactory(fa);
4:这个要设制classpath了,麻烦
  Resource res = new ClassPathResource("com/springinaction/chapter01/hello/hello.xml");
  BeanFactory factory=new XmlBeanFactory(res);
好了,用了上面那种方法都可以调用getBean("your bean name")了,
eg: BeanFactory factory=new XmlBeanFactory(fa);
      hello he=(hello)factory.getBean("hello");
              he.getHello();

================================================================================

 

 

 

 

贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰贰

http://babycountry.spaces.live.com/blog/cns!18767b1e2eb6d0e1!236.entry

spring 读取注册bean的一些方法(转)

       我现在在做的东西,主要用到了框架是struts2+hibernate+spring开发一个上传,下载,播放视频,听歌的东西,在做到获得到注册bean的时候,我想通过在web.xml配置context-param中获得,但老也不成功,后来在网站上看到别人写的,共同分享:
          通过几个项目的实践总结一下几种获得spring里注册Bean的方法:
一:方法一(多在struts框架中)继承BaseDispatchAction
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
package com.mas.wawacommunity.wap.web.action;
 
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
 
import com.mas.wawacommunity.wap.service.UserManager;
 
public class BaseDispatchAction extends DispatchAction {
    /**
    * web应用上下文环境变量
    */
    protected WebApplicationContext ctx;
 
    protected UserManager userMgr;
 
    /**
    * 获得注册Bean     
    * @param beanName String 注册Bean的名称
    * @return
    */
    protected final Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }
 
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
              javax.servlet.http.HttpServletRequest request,
              javax.servlet.http.HttpServletResponse response) {     
        return mapping.findForward("index");
    }
 
    public void setServlet(ActionServlet servlet) {
        this.servlet = servlet;
        this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
        this.userMgr = (UserManager) getBean("userManager");
    }         
}

action调用:
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
package com.mas.wawacommunity.wap.web.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
 
import com.mas.wawacommunity.wap.model.News;
import com.mas.wawacommunity.wap.service.NewsManager;
 
public class NewsAction extends BaseDispatchAction {
  NewsManager newsManager;       
    
    public void setServlet(ActionServlet servlet) {
        super.setServlet(servlet);
        newsManager = (NewsManager) this.getBean("newsManager");         
  }
    
    /**
    * 得到新闻列表
    * @param mapping
    * @param form
    * @param request
    * @param resp
    * @return
    */
    public ActionForward getNewsList(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse resp) {
        int category = Text.parseInt(request, "category", 0);
        int pageNo = Text.parseInt(request, "pageNo", 1);
        int pageSize = Text.parseInt(request, "pageSize", 9);
        PageRoll pageRoll = newsManager.getAllNews(category, pageNo, pageSize);               
        request.setAttribute("pageRoll", pageRoll);
        return mapping.findForward("news.list");
    }
}


二:方法二实现BeanFactoryAware
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
46
47
48
49
50
51
52
53
package com.anymusic.oa.commons.service;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
 
/**
* Created by IntelliJ IDEA.
* User: Weany
* Date: 2006-4-2
* Time: 2:46:51
* To change this template use File | Settings | File Templates.
*/
public class ServiceLocator implements BeanFactoryAware {
    private static BeanFactory beanFactory = null;
 
    private static ServiceLocator servlocator = null;
 
    public void setBeanFactory(BeanFactory factory) throws BeansException {
        this.beanFactory = factory;
    }
 
    public BeanFactory getBeanFactory() {
        return beanFactory;
    }
 
    /**
    * 创建读取Bean服务类实例(从spring.xml中加载)
    * <bean id="serviceLocator" class="com.am.oa.commons.service.ServiceLocator" singleton="true" />
    */
    public static ServiceLocator getInstance() {
        if (servlocator == null)
              servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator");
        return servlocator;
    }
 
    /**
    * 根据提供的bean名称得到相应的服务类     
    * @param servName bean名称     
    */
    public static Object getService(String servName) {
        return beanFactory.getBean(servName);
    }
 
    /**
    * 根据提供的bean名称得到对应于指定类型的服务类
    * @param servName bean名称
    * @param clazz 返回的bean类型,若类型不匹配,将抛出异常
    */
    public static Object getService(String servName, Class clazz) {
        return beanFactory.getBean(servName, clazz);
    }
}


action调用:
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
package com.anymusic.oa.webwork;
 
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;
 
public class UserAction extends BaseAction implements Action,ModelDriven{
    
    private Users user = new Users();
    protected ServiceLocator service = ServiceLocator.getInstance();
    UserService userService = (UserService)service.getService("userService");
 
    public String execute() throws Exception {         
        return SUCCESS;
    }
 
  public Object getModel() {
        return user;
    }     
    
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();         
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);     
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}


三:方法三实现ApplicationContextAware

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.easou.framework.common.util;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
public class SpringContextUtil implements ApplicationContextAware {
  private static ApplicationContext applicationContext;     //Spring应用上下文环境
 
  /**
  * 实现ApplicationContextAware接口的回调方法,设置上下文环境   
  * @param applicationContext
  * @throws BeansException
  */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
  }
 
  /**
  * @return ApplicationContext
  */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
 
  /**
  * 获取对象   
  * @param name
  * @return Object 一个以所给名字注册的bean的实例
  * @throws BeansException
  */
  public static Object getBean(String name) throws BeansException {
    return applicationContext.getBean(name);
  }
 
  /**
  * 获取类型为requiredType的对象
  * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
  * @param name       bean注册名
  * @param requiredType 返回对象类型
  * @return Object 返回requiredType类型对象
  * @throws BeansException
  */
  public static Object getBean(String name, Class requiredType) throws BeansException {
    return applicationContext.getBean(name, requiredType);
  }
 
  /**
  * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true 
  * @param name
  * @return boolean
  */
  public static boolean containsBean(String name) {
    return applicationContext.containsBean(name);
  }
 
  /**
  * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
  * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)   
  * @param name
  * @return boolean
  * @throws NoSuchBeanDefinitionException
  */
  public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.isSingleton(name);
  }
 
  /**
  * @param name
  * @return Class 注册对象的类型
  * @throws NoSuchBeanDefinitionException
  */
  public static Class getType(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getType(name);
  }
 
  /**
  * 如果给定的bean名字在bean定义中有别名,则返回这些别名   
  * @param name
  * @return
  * @throws NoSuchBeanDefinitionException
  */
  public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getAliases(name);
  }
}



action调用:
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
package com.anymusic.oa.webwork;
 
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;
 
public class UserAction extends BaseAction implements Action,ModelDriven{
    
    private Users user = new Users();     
    UserService userService = (UserService) SpringContextUtil.getBean("userService");
    
    public String execute() throws Exception {         
        return SUCCESS;
    }
 
  public Object getModel() {
        return user;
    }     
    
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();         
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);     
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics