有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Spring java config EJB代理不工作

在使用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
}

我的春豆。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文件。根据the documentation的说法,本地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>

但是,如果我从AppConfig中删除@ImportResource并将此@Bean方法改为@Bean方法,则部署失败,因为无法实例化控制器(找不到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) 个答案

  1. # 1 楼答案

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

    具体来说,引入一个单独的配置类并在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
    }