spring注解驱动编程

一、Annotation装配(@Configuration)
1,替代Xml装配
在resource/META-INF/spring目录下添加context.xml
context.xml的内容如下:




    
    
        
    

测试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> 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> 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> webAppInitializerClasses我关心的类对象是WebApplicationInitializer.class类型的。所以会扫描classpath下的WebApplicationInitializer的子类,放到Set>集合中。
在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中添加:

war

(4)使用tomcat插件打包:


        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.1
                
                    
                        tomcat-run
                        
                            exec-war-only
                        
                        package
                        
                            
                            foo
                        
                    
                
            
        
    

(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






(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一起使用,因为有些配置必须在某些类存在的情况下才会需要。

你可能感兴趣的:(spring注解驱动编程)