应用上下文bean [英] Application context bean

查看:145
本文介绍了应用上下文bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从应用程序上下文中提取bean。

I am trying to extract the bean from application context.

所以我定义了类:

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
        applicationContext = _applicationContext;

    }

}

和我的applicationContext.xml

and in my applicationContext.xml

<bean id="workflowService" class="com.mycompany.util.WorkflowService">
    <bean id="applicationContextProvider" class="com.mycompany.util.ApplicationContextProvider"></bean>
   <context:annotation-config />

但是在我的代码中,当我尝试:

However in my code when I try:

WorkflowService service  = (WorkflowService) ApplicationContextProvider.getApplicationContext().getBean("workflowService");

我得到:


java.lang.ClassCastException:$ Proxy40无法强制转换为com.mycompany.util.WorkflowService

java.lang.ClassCastException: $Proxy40 cannot be cast to com.mycompany.util.WorkflowService

EDITED

WorkflowService代码:

WorkflowService code:

public class WorkflowService implements Serializable {
   ...
   @PostConstruct
       public void init() {
   }
   ...
   @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
       public Collection<lData> findData(Integer contractId) {
   }    
}


推荐答案

我猜 WorkflowService 是一个实现至少一个接口的类(你没有提供足够的代码)。您正在尝试从Spring查找确切的类,而您应该要求其中一个接口。

I guess WorkflowService is a class implementing at least one interface (you haven't provided enough code). You are trying to lookup the exact class from Spring, while you should ask for one of the interfaces.

这是因为Spring大多数情况下将bean包装在几个代理中(例如交易的)。如果类实现至少一个接口,则生成的代理实现所有接口,但不能转换为原始类。如果该类没有实现任何接口(通常被认为是重量级服务的不良做法,尽管有问题),Spring将使用原始类的CGLIB子类。在这种情况下,您的代码有效。

This is because Spring most of the time wraps beans in several proxies (e.g. transactional ones). If the class implements at least one interface, resulting proxy implements all of them, but cannot be cast into original class. If the class does not implement any interfaces (commonly considered a bad practice for heavyweight services, questionable though), Spring will use CGLIB subclassing from original class. In this case you code would be valid.

这篇关于应用上下文bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆