BeanFactory 和 ApplicationContext 区别

欢迎光临我的博客[http://poetize.cn],前端使用Vue2,聊天室使用Vue3,后台使用Spring Boot

区别

BeanFactory:

	Spring里面最低层的接口,提供了最简单的容器的功能,只提供了实例化对象和拿对象的功能

	BeanFactory在启动的时候不会去实例化Bean,中有从容器中拿Bean的时候才会去实例化


ApplicationContext:

	应用上下文,继承BeanFactory接口,它是Spring的一各更高级的容器,提供了更多的有用的功能

		1) 国际化(MessageSource)

		2) 访问资源,如URL和文件(ResourceLoader)

		3) 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层  

		4) 消息发送、响应机制(ApplicationEventPublisher)

		5) AOP(拦截器)

	ApplicationContext在启动的时候就把所有的非延迟加载Bean全部实例化了。它还可以为Bean配置 lazy-init=true 来让Bean延迟实例化

国际化(MessageSource)

<!-- 资源国际化 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	<property name="basenames">
		<list>
			<value>properties/messages</value>	<!-- proerties包下的以messages为主要名称的properties文件 -->
		</list>
	</property>
</bean>

Spring访问资源(ResourceLoader)

ApplicationContext acxt =new ClassPathXmlApplicationContext("/applicationContext.xml");

1.通过虚拟路径来存取:当资源位于CLASSPATH路径下时,可以采用这种方式来存取。

	Resource resource = acxt.getResource("classpath:messages_en_CN.properties");

2.通过绝对路径存取资源文件。

	Resource resource = acxt.getResource("file:F:/messages_en_CN.properties");

3.相对路径读取资源文件。

	Resource resource = acxt.getResource("/messages_en_CN.properties");

Spring载入多个上下文

方法一:

	<import resource="applicationContext.xml"/>


方法二:

	<context-param>
		<param-name>contextConfigLocation</param-name>

		<param-value>
			classpath:applicationContext-security.xml,applicationContext-dao.xml,applicationContext-Service.xml
		</param-value>
	</context-param>

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

Spring的AOP(常用的是拦截器)

一般拦截器都是实现HandlerInterceptor,其中有三个方法preHandle、postHandle、afterCompletion

	1. preHandle:执行controller之前执行

	2. postHandle:执行完controller,return modelAndView之前执行,主要操作modelAndView的值

	3. afterCompletion:controller返回后执行


配置:

	<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/logout"/>
            <ref bean="interceptor"  />
        </mvc:interceptor>  
    </mvc:interceptors>  


public class Interceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
            throws Exception {
        return true;
    }
}
posted @ 2019-09-23 20:31  LittleDonkey  阅读(281)  评论(0编辑  收藏  举报