Spring @Autowired(required = true) is null [duplic

2019-03-04 03:21发布

I have a webmodule with JSF 2 end Spring 4.3. In a backing bean I use @Autowired for DI of a service of a JAR. In EAR module there are WAR, JAR with @Service Spring and JAR with Spring configuration file.

Below a web.xml snippet:

    <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>

When I Use @Autowired(required=null) in a Backing Bean the value is null (there is not any exception). My JSF bean

@Component
@ManagedBean
@ViewScoped
public class PortfolioController {


    @Autowired(required = true)
    private PortfolioService portfolioService;

...

Can you help me, please.

2条回答
男人必须洒脱
2楼-- · 2019-03-04 03:52

PortfolioController is considered a JSF context bean adding @Component to @ManagedBean is totally wrong you can't mark same class as bean in two different contexts (JSF and Spring ).

Two solutions either make PortfolioController a spring bean thus remove the @ManagedBean and @ViewScoped or inject PortfolioController via JSF injection annotation @ManagedProperty

@ManagedProperty("#{portfolioService}")
private PortfolioService portfolioService;
查看更多
乱世女痞
3楼-- · 2019-03-04 03:55

if the applicationContext.xml is in your jar dependency, then you need to add asterisk after classpath:

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

With the asterisk spring search files applicationContext.xml anywhere in the classpath not only the current project.

查看更多
登录 后发表回答