spring mvc环境之引入spring容器(七)

spring mvc环境之引入spring容器实现对项目bean的依赖注入、控制翻转等

因为之前pom.xml引入了spring-web,它本身就要依赖于核心包

------------

然后在web.xml配置监听器,引入spring容器的上下文(并引入相关配置文件).

 <!--  加载Spring容器配置 -->
  <!-- 配置ContextLoaderListener 监听器 -->
  <!-- 作用:ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息.因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--  设置Spring容器加载所有的配置文件的路径 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

 

spring配置文件中可以写很多配置内容(启用注解、扫描service不扫描controller,数据库bean,事务相关,mybaits,aop...)之后记录

resources/applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

 

先加一个扫描所有实体类的配置(除了控制器@Controller,因为控制器在spring-mvc中管理)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- spring希望管理所有的业务逻辑组件,(数据源,与mybaits的整合,事务控制)等... -->


    <!-- 1.也是扫描所有组件,但是不扫描 controller标注的控制器,其他的都拿到-->
    <context:component-scan base-package="com.cc8w">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    
</beans>

 

posted @ 2022-12-07 17:24  与f  阅读(75)  评论(0)    收藏  举报