记录一次Spring父容器与SpringMVC子容器学习遇到的异常

Spring父容器:

 web.xml初始化:

<!-- 启动spring -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>

<!-- 加载contextConfigLocation -->
<listener>
	<!-- spring会初始化一个启动上下文,这个上下文被称为根上下文,即WebApplicationContext,
		这是一个接口类,确切的说,其实际的实现类是XmlWebApplicationContext。
		这个就是spring的IoC容器,其对应的Bean定义的配置由web.xml中的context-param标签指定 -->
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring子容器:

 web.xml初始化:

<!-- 加载Springmvc -->
<servlet>
	<servlet-name>manage-servlet</servlet-name>
	<!-- 建立自己的IoC上下文,用以持有spring mvc相关的bean -->
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/manage-servlet.xml</param-value>
	</init-param>
	<!-- 随容器自动启动完成初始化 -->
	<load-on-startup>1</load-on-startup>
</servlet>

  1. SpringMVC子容器可以访问Spring父容器:可以直接注入父类bean到子类容器中
  2. Spring父容器不可以访问SpringMVC子容器

然而使用使用spring自带的占位符替换功能:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer加载properties文件时候,子容器并不能访问到父容器中的bean,配置如下

applicationContext.xml
<!-- 使用spring自带的占位符替换功能 -->
<bean
	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<!-- 允许JVM参数覆盖 -->
	<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
	<!-- 忽略没有找到的资源文件 -->
	<property name="ignoreResourceNotFound" value="true" />
	<!-- 配置资源文件 -->
	<property name="locations">
		<list>
			<value>classpath:jdbc.properties</value>
			<value>classpath:evn.properties</value>
		</list>
	</property>
</bean>

分析:

使用@PostConstruct 将对象注入打印到控制台,发现有两次初始化,一次是父容器初始,第二次是子容器初始时候,第一次能正常取到properties对象,第二次时不能获取到值

//子容器的直接访问
@Value("${REPOSITORY_PATH}")//properties文件中  REPOSITORY_PATH=D:\\home\\download
private String REPOSITORY_PATH;
@PostConstruct
public void log() {
	System.out.println("初始化==================" + REPOSITORY_PATH + "==========");
}

解决方法:

重新写一个类将xml的中bean注入到一个父容器中的一个service类,供其他子容器调用

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class PropertieService {
	@Value("${REPOSITORY_PATH}")
	public String REPOSITORY_PATH;
	
	@Value("${IMAGE_BASE_URL}")
	public String IMAGE_BASE_URL;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

被撞傻的杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值