Spring----注解的配置及启动

1.在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service@Repository这些注解的类,则把这些类注册为bean

    <context:component-scan base-package="com.**" />

注意:1)@Controller, @Service, @Repository是@Component的细化,这三个注解比@Component带有更多的语义,它们分别对应了控制层、服务层、持久层的类。一般来说@Controller(控制层) 是action入口,调用@Service(业务层) ,Service再调用@Repository (持久层)完成数据持久化。

           2)如果只想扫描指定包下面的@Controller,

    <context:component-scan base-package="com.**">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

2.BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入

 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

注意:@Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。

3.配置事务管理器,并且支持注解驱动,让@Transactional事务注解生效

<!--添加tx命名空间-->
... xmlns:tx
="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" ... http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd ...
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven />

4.启动Spring MVC的注解功能

 <!-- 1.从类路径下加载Spring配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/applicationContext.xml</param-value>
  </context-param>-->
<!-- 2.负责启动Spring容器的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<!-- 3.Spring MVC的主控Servlet--> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

注意:1.一个web.xml可以配置多个DispatcherServlet,通过其<servlet-mapping>的配置,让每个DispatcherServlet处理不同的请求。

           2.默认情况下Spring  MVC根据Servlet的名字查找WEB-INF下的<servletName>-servlet.xml作为Spring  MVC的配置文件。我们也可以通过contextConfigLocation参数指定配置文件。

    <!-- 在Spring MVC的配置文件中,定义JSP文件的位置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
原文地址:https://www.cnblogs.com/mcahkf/p/8267256.html