整合Spring和JSF

1.在web配置文件里面声明ContextLoaderListener。

声明了ContextLoaderListener之后,Spring XML配置文件才会自动加载,不设置这个,就得在应用程序里面使用

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

来获取上下文。

当使用到多个配置文件的时候,例如applicationContext-dao.xml,applicationContext-service.xml,那么我们需要设置contextConfigLocation,可以使用通配符,默认是查找WEB-INF/applicationContext.xml。配置如下:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这里需要注意,我们如果之前习惯使用ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");这种方式获取上下文,然后注入(这时候applicationContext.xml文件放在类路径底下),那么我们有可能会这么设置:

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

2.在faces-context.xml文件配置DelegatingVariableResolver

在<faces-config>下添加一下内容:

<application>
<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
</application>

那么,我们可以在使用到managedBean的时候就会自动注入一个Service的实例,例如:

applicationContext配置文件:

<!-- 声明service的bean -->
<bean id="fruitService" class="service.FruitServiceImpl">
<property name="fruitDAO" ref="fruitDAO"/>
</bean>

faces-context配置文件:

<managed-bean>
<managed-bean-name>fruitList</managed-bean-name>
<managed-bean-class>backingbean.FruitList</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>fruitService</property-name>
<value>#{fruitService}</value>
</managed-property>
</managed-bean>

这里注意,FruitList这个backingbean里面引用了一个FruitService fruitService,并且还有getter,setter方法,声明为managedBean的时候可以通过#{fruitService}这个值给fruitService注入,#{fruitService}里面的绑定值对应<bean>声明的id值。

另外,当我们使用这个fruitService获取一个List的时候,不能够在构造方法里面获取,要在getFruitService里面获取。例如:

public FruitList(){
fruitList = fruitService.findAllFruit();
}

这是错误的,会抛出空指针异常。因为在构造方法里面使用fruitService的时候,fruitService还没有被注入,只有当我们实例化managedBean之后才可以通过setter方法给fruitService注入。例如:

public List<Fruit> getFruitList() {
fruitList = fruitService.findAllFruit();
return fruitList;
}

这样fruitService才会被注入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值