Spring @Autowired(required = true)为null

时间:2016-07-24 11:28:03

标签: spring jsf dependency-injection

我有一个带有JSF 2结束Spring 4.3的webmodule。在支持bean中,我使用@Autowired作为JAR服务的DI。在EAR模块中有WAR,JAR带有@Service Spring和带有Spring配置文件的JAR。

web.xml代码段

下方
    <context-param>
        <param-name>locatorFactorySelector</param-name>
        <param-value>classpath:beanRefContext.xml</param-value>
    </context-param>

    <context-param>
        <param-name>parentContextKey</param-name>
        <param-value>sharedContext</param-value>
    </context-param>
    <context-param>
    <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

applicationContext.xml

    <context:annotation-config />
    <context:spring-configured />
<!-- package of @Service class in jar module in EAR-- >
    <context:component-scan base-package="com.ipdb.service" /> 

beanRefContext.xml:

<bean id="sharedContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">    <constructor-arg>
    <list>
        <value>spring-ctx.xml</value>
    </list>
</constructor-arg>    </bean>

当我在Backing Bean中使用@Autowired(required=null)时,值为null(没有任何异常)。我的JSF bean

@Component
@ManagedBean
@ViewScoped
public class PortfolioController {


    @Autowired(required = true)
    private PortfolioService portfolioService;

...

请帮助我。

2 个答案:

答案 0 :(得分:2)

PortfolioController被视为JSF上下文bean将@Component添加到@ManagedBean是完全错误的,你不能在两个不同的上下文中将同一个类标记为bean({{1} }和JSF)。

两个解决方案要么使Spring成为一个spring bean,要通过PortfolioController注入注释@ManagedBean <删除@ViewScopedPortfolioController或注入JSF / p>

@ManagedProperty

答案 1 :(得分:0)

如果applicationContext.xml在你的jar依赖项中,那么你需要在classpath之后添加星号:

  <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>

使用星号弹簧搜索文件applicationContext.xml在类路径中的任何位置不仅是当前项目。

相关问题