Spring java配置EJB代理无法正常工作

时间:2014-03-03 08:41:30

标签: java spring spring-mvc ejb-3.0

在使用Spring的java配置类时,我遇到了使EJB bean工作的问题。 具体来说,我有以下工作:

@Configuration
@ComponentScan(basePackages = "com.company.web.config")
@ImportResource(value = {"classpath:spring-beans.xml"})
public class AppConfig {
}

@Configuration
@ComponentScan(basePackages = "com.company.web")
public class WebConfig extends WebMvcConfigurationSupport {
   // basic Spring MVC setup omitted
}

我的spring-beans.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

    <jee:local-slsb id="fooService" jndi-name="java:app/model/FooServiceBean!com.company.ejb.FooService"
      business-interface="com.company.ejb.FooService" />
</beans>

使用此配置,一切正常,我可以这样做:

@Controller
public class HomeController {
    private final FooService fooService;

    @Autowired
    public MyPageController(FooService fooService){
        this.fooService = fooService;
    }

    // request methods
}

现在我试图摆脱XML文件。根据{{​​3}},local-slsb应该是等价的

<bean id="fooService"
        class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="java:app/model/FooServiceBean!com.company.ejb.FooService"/>
    <property name="businessInterface" value="com.company.ejb.FooService"/>
</bean>

但是,如果我从@ImportResource中移除AppConfig并改为使用此@Bean方法,则部署失败,因为无法实例化Controller(找不到FooService的autowire候选者):

@Bean
    public LocalStatelessSessionProxyFactoryBean fooService(){
        LocalStatelessSessionProxyFactoryBean factory = new LocalStatelessSessionProxyFactoryBean();
        factory.setBusinessInterface(FooService.class);
        factory.setJndiName("java:app/model/FooServiceBean!com.company.ejb.FooService");
        return factory;
    }

为什么这不起作用的任何想法?我使用的是Spring 4.0.2版。

1 个答案:

答案 0 :(得分:2)

似乎问题与读取配置的顺序有关,可能还有双重配置加载。

具体来说,引入一个单独的配置类并在WebConfig之前导入它似乎可以解决问题,如下所示:

@Configuration
@Import({EJBConfig.class, WebConfig.class})
public class AppConfig {
}

@Configuration
public class EJBConfig {
    @Bean
    public LocalStatelessSessionProxyFactoryBean fooService(){
        LocalStatelessSessionProxyFactoryBean factory = new LocalStatelessSessionProxyFactoryBean();
        factory.setBusinessInterface(FooService.class);
        factory.setJndiName("java:app/model/FooServiceBean!com.company.ejb.FooService");
        return factory;
    }
}

@Configuration
@ComponentScan(basePackages = "com.company.web")
public class WebConfig extends WebMvcConfigurationSupport {
   // basic Spring MVC setup omitted
}