spring注解驱动编程

一、Annotation装配(@Configuration)
1,替代Xml装配
在resource/META-INF/spring目录下添加context.xml
context.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--传统定义方式-->
    <bean id="user" class="com.gupao.annotationdrivendevelopment.domain.User">
        <property name="name" value="cassie"/>
    </bean>
</beans>

测试demo:

package com.gupao.annotationdrivendevelopment.bootstrap;

import com.gupao.annotationdrivendevelopment.domain.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sun.tools.java.ClassPath;

/**
 * xml配置引导程序
 *
 */
public class XmlConfigBootstrap {


    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext();

        applicationContext.setConfigLocation("classpath:META-INF/Spring/Context.xml");

        applicationContext.refresh();

        User user = applicationContext.getBean("user",User.class);

        System.out.println(user.getName());
    }
}

2,采用annotation注入User对象,怎么写?
写一个UserConfiguration,配置要注入的User对象信息。

package com.gupao.annotationdrivendevelopment.config;

import com.gupao.annotationdrivendevelopment.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**annotation 驱动的写法,利用java code来完成配置
 * User的配置bean
 * 缺点是有一点硬编码
 */
@Configuration
public class UserConfiguration {

    @Bean
    public User user(){
        User user = new User ();
        user.setName("Cassie1");
        return user;
    }
}

写一个Controller

package com.gupao.annotationdrivendevelopment.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    /**
     * @GetMapping("/hello")
     * 注解的方式,元编程的方式,输入描述性的信息。
     *  这个信息不是通过代码组装的方式来进行暴露,而是通过一个元信息曝露。
     *  在框架层面会把我这个元信息放到相应的Mapping中。
     *
     */
    @GetMapping("/hello")
    public String hello(){
        return "Hello World!";
    }
}

二、Web自动装配(@AutoConfiguration)
1,我们的DemoController为什么会被执行?
因为 DispatcherServlet (前段控制器)会把请求分发过来,在容器启动的时候会自动装配进来。通过DispatcherServletConfiguration 会配置 DispatcherServlet 。
DispatcherServletConfiguration 是 DispatcherServletAutoConfiguration 的内部类。
那么 DispatcherServlet 是什么时候被加载的?
DispatcherServletAutoConfiguration # dispatcherServletRegistration(DispatcherServlet dispatcherServlet)方法中

registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup());

所以DispatcherServletAutoConfiguration会负责 DispatcherServlet的自动装配。
2,Servlet规范中规定的 LoadOnStartup 是设置Servlet的加载顺序?

Servlets are initialized either lazily at request processing time or eagerly during
deployment. In the latter case, they a

3,spring webflux兼容servlet容器(tomcat)和非servlet容器(Netty)
4,在 ServletRegistrationBean 中,里面封装了一个Servlet,存储该Servlet注册到容器中所需的信息,比如 urlMappings,loadOnStrartup。
5,ServletRegistrationBean # onStartup()中,将当前类所代表的servlet 注入到容器中。servletContext.addServlet(name, this.servlet);

6,我们需要在合适的时机将相应的东西(Servlet 或者 Filter)加载进来,所以我要了解生命周期。Servlet 容器启动相关的两个类:
(1)ServletContextListener:有两个生命周期

public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce);

servlet规范中的pluggability:
Spring mvc或者spring security中都会涉及到。

(2)ServletContainerInitializer:
ServletContainerInitializer 的实现类是通过SPI的方式配置的,比如,spring对ServletContainerInitializer的实现类也即是SpringServletContainerInitializer,
配置在SpringServletContainerInitializer所在的jar包org.springframework.web的
/META-INF/services/javax.servlet.ServletContainerInitializer中。

void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;

注意,ServletContainerInitializer # onStartup()
在 ServletContextListener # contextInitialized()之前执行。

ServletContainerInitializer -> onStartup 当容器启动时
ServletContextListener ->contextInitialized 当ServletContext初始化完成时

以前我们通过xml文件加载的,我们在web.xml中配置:
org.springframework.web.context.ContextLoaderListener
ContextLoaderListener继承ContextLoader,实现ServletContextListener,当ServletContext初始化完成时就会执行contextInitialized

我们在spring boot中是没有xml文件的,完全通过annotation驱动的。
那么annotation 是怎样驱动的?
我们看看spring web对ServletContainerInitializer的实现SpringServletContainerInitializer:
onStartup方法签名:

public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException

默认扫描 WEB-INF/classes 和 WEB-INF/lib
->这两个目录其实就是classpath

@HandlesTypes(WebApplicationInitializer.class):

This annotation is used to declare an array of application classes which are 
passed to a {@link javax.servlet.ServletContainerInitializer}

表示Set<Class<?>> webAppInitializerClasses我关心的类对象是WebApplicationInitializer.class类型的。所以会扫描classpath下的WebApplicationInitializer的子类,放到Set<Class<?>>集合中。
在Servlet规范中:

The container uses the HandlesTypes annotation to determine when to invoke the initializer's onStartup method. When examining the classes of an application to see if they match any of the criteria specified by the HandlesTypes annotation of a ServletContainerInitializer.

(3)WebApplicationInitializer的子类AbstractContextLoaderInitializer是干嘛用的?
Abstract ContextLoader Initializer:
AbstractContextLoaderInitializer#registerContextLoaderListener(ServletContext)
通过rootAppContext去创建一个ContextLoaderListener,ContextLoaderListener是监听rootAppContext的生命周期的监听器。
AbstractContextLoaderInitializer -> ContextLoaderListener
负责加载ServletContext

(4)AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer
AbstractDispatcherServletInitializer ->DispatcherServlet
负责 initialize DispatcherServlet

(5)AbstractAnnotationConfigDispatcherServletInitializer extends AbstractDispatcherServletInitializer:
AbstractAnnotationConfigDispatcherServletInitializer ->
Annotation + Config + DispatcherServlet

(6)WebApplicationInitializer的继承关系:
WebApplicationInitializer
|-AbstractContextLoaderInitializer
|-AbstractDispatcherServletInitializer
|-AbstractAnnotationConfigDispatcherServletInitializer

三、实现:不用Spring boot,将 DispatcherServlet 加载起来.
不用spring boot,我们依然可以达到自动装配spring web mvc的效果。使用java code和annotation的方式进行配置bean。而且实现了java -jar的方式启动
1,实现Spring Web mvc自动装配
(1)定义一个AbstractAnnotationConfigDispatcherServletInitializer的子类AutoConfigDispatcherServletInitializer。

package com.gupao.spring.webmvc.auto.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AutoConfigDispatcherServletInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {



    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }


    protected Class<?>[] getServletConfigClasses() {
        //把自己写的配置bean,配置在这里
             return new Class[]{SpringWebmvcConfiguration.class};
    }

    protected String[] getServletMappings() {
        //配置映射路径
        return new String[]{"/*"};
    }
}

(2),定义一个Spring mvc配置类:

@Configuration
@ComponentScan(basePackages = "com.gupao.spring.webmvc.auto")
public class SpringWebmvcConfiguration {
}

(3),改变打包方式:
pom.xml中添加:

<packaging>war</packaging>

(4)使用tomcat插件打包:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <id>tomcat-run</id>
                        <goals>
                            <goal>exec-war-only</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <!--servlet context path-->
                            <path>foo</path>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

(5)写一个controller

package com.gupao.spring.webmvc.auto.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @GetMapping
    public String index(){
        return "spring web mvc 自动装配!";
    }
}

(6)修改main/webapp/WEB-INF/web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee
        https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">



</web-app>

(7)maven 打包命令:

mvn -Dmaven.test.skip -U clean package

(8)启动服务

java -jar spring-webmvc-autoconfig-1.0-SNAPSHOT-war-exec.jar

(9)远程debug启动:

java -jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=9527 spring-webmvc-autoconfig-1.0-SNAPSHOT-war-exec.jar

四、条件装配(@OnConditional)

@Configuration很多时候都会和@ConditionalOnClass一起使用,因为有些配置必须在某些类存在的情况下才会需要。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,321评论 6 543
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,559评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,442评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,835评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,581评论 6 412
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,922评论 1 328
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,931评论 3 447
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,096评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,639评论 1 336
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,374评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,591评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,104评论 5 364
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,789评论 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,196评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,524评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,322评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,554评论 2 379

推荐阅读更多精彩内容