spring boot

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot相关的知识,希望对你有一定的参考价值。

Spring boot

简述

    spring boot使用习惯优于配置”的理念,可以让项目快速的运行;

    使用spring boot很容易创建一个独立运行(内嵌servlet容器)基于spring框架的项目,开发者可以不用或者只使用很少的spring配置。

基本配置

    入口类:spring boot通常有一个名为*Application的入口类,入口类中有一个main方法。

        @SpringBootApplication是spring boot的核心注解,它是一个组合注解:

        @Configuration

        @EnableAutoConfiguration

        @ComponentScan

外部配置

        spring boot允许使用properties文件,命令行等作为外部配置。

        命令行:如spring boot是可以基于jar包运行的,

        java -jar xx.jar --server.port=9090

常规属性配置:

        application.properties文件中:

        book.authour=sun

        book.name=spring boot

        入口类:

        @RestController

        @SpringBootApplication

        public class DemoApplication {

        

            @Value("${book.name}")

        private String bookname;

        

        @RequestMapping("/")

        String index(){

            return "Hello Spring boot,bookname:"+bookname;

        }

        

        public static void main(String[] args) {

        

            SpringApplication.run(DemoApplication.class, args);

        }

        

        }

        技术分享图片

类型安全的配置:


        为了简化每个属性都由@value对应,通过@ConfigurationProperties将properties属性和一个bean及其属性关联。

        @Component

        @ConfigurationProperties(prefix = "book")//使用的配置参数的前缀

        @PropertySource("classpath:book.properties")//配置文件的位置

        public class Book {

        

            private String name;

        

            public String getName() {

                return name;

            }

        

            public void setName(String name) {

                this.name = name;

            }

        }

        @RestController

        @SpringBootApplication

        public class DemoApplication {

        

            @Autowired

            private Book book;

        

            @RequestMapping("/")

            String index(){

                return "Hello Spring boot,bookname:"+book.getName();

            }

        

            public static void main(String[] args) {

        

                SpringApplication.run(DemoApplication.class, args);

            }

        }

        技术分享图片

profile配置

    profile是spring boot用来针对不同的环境对不同的配置提供支持的,全局profile配置使用application-{profile}.properties,通过在application.properties中设置spring.profile.active=xx来制定活动的profile。


spring boot中servlet,filter,listener的两种注册方式

        传统的java ee是在web.xml中配置filter等信息,而spring boot支持两种方式:代码注册;注解注册。

        1.代码注册:

                    创建自定义的filter

                    public class TestFilter implements Filter {

                      @Override

                      public void init(FilterConfig filterConfig) throws ServletException {

                      }

                     @Override

                      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)

                          throws IOException, ServletException {

                        System.out.println("TestFilter");

                      }

               @Override

              public void destroy() {

              }

            }

            在配置类中注册过滤器:

            @Configuration

             public class WebConfig {

            @Bean

                 public FilterRegistrationBean getDemoFilter(){

                 TestFilter demoFilter = new TestFilter();

                     FilterRegistrationBean registrationBean=new FilterRegistrationBean();

                     registrationBean.setFilter(demoFilter);

                     List<String> urlPatterns=new ArrayList<String>();

                     urlPatterns.add("/*");                            //拦截路径,可以添加多个

                     registrationBean.setUrlPatterns(urlPatterns);

                     registrationBean.setOrder(1);

                     return registrationBean;

                 }

            }

    2.注解注册

                创建自定义的filter,加@WebFilter注解

                @Order(1)

                @WebFilter(filterName = "testFilter2”, urlPatterns = "/*")

                public class TestFilter2 implements Filter {

                  @Override

                  public void init(FilterConfig filterConfig) throws ServletException {

                 

                  }

                  @Override

                  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)

                      throws IOException, ServletException {

                    filterChain.doFilter(servletRequest,servletResponse);

                  }

                  @Override

                  public void destroy() {

                  }

                }

                在工程入口加上注解@ServletComponentScan,实现自动的扫描注册(带有WebFilter,WebServlet,WebListener注解的类),不用在代码中写registrationBean.setFilter

                        @SpringBootApplication

                @ServletComponentScan

                public class SpringBootSimpleApplication {

                  public static void main(String[] args) {

                    SpringApplication.run(SpringBootSimpleApplication.class, args);

                  }

                }

Spring boot SSL配置

            SSL(security sockets layer安全套接层)位于TCP/IP协议和各种应用层协议(如HTTP)之间,为数据通信提供安全支持。采用了SSL之后,HTTP就有了HTTPS的加密,证书和完整性保护这些功能。

            1.使用SSL首先需要生成证书,可以通过jdk里的证书管理工具keytool生成自签名的证书;

            2.配置SSL:spring boot允许在application.properties中配置http或https,但是只能配置一个,另外一个需要以编程的方式配置。https比较复杂,所以在配置文件中配置https信息:

            #https端口号.  

        server.port: 443  

        #证书路径.  

        server.ssl.key-store: classpath:keystore.p12  

        #证书密码

        server.ssl.key-store-password: 123456  

        #秘钥库类型  

        server.ssl.keyStoreType: JKS  

        #证书别名  

        server.ssl.keyAlias: tomcat 

   3.此时,可以在页面访问https的网页,但是访问不到http的网页,还需要实现http到https的重定向

      4.代码中配置http信息,并添加tomcat的connector,实现自动跳转

     @Bean  

    public EmbeddedServletContainerFactory servletContainer() {  

      TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {  

   

           @Override  

           protected void postProcessContext(Context context) {  

              SecurityConstraint securityConstraint = new SecurityConstraint();  

              securityConstraint.setUserConstraint("CONFIDENTIAL");  

              SecurityCollection collection = new SecurityCollection();  

              collection.addPattern("/*");  

              securityConstraint.addCollection(collection);  

              context.addConstraint(securityConstraint);  

           }  

       };  

       //添加连接配置,http的配置信息.  

       tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());  

       return tomcat;  

    }  


    /**  

     * 配置http连接信息. 

     */  

    private Connector initiateHttpConnector() {  

       Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");  

       connector.setScheme("http");  

       connector.setPort(8080);  

       connector.setSecure(false);  

       connector.setRedirectPort(443);  

       return connector;  

    }  

    5.此时访问http://localhost:8080自动转到https://localhost:443


以上是关于spring boot的主要内容,如果未能解决你的问题,请参考以下文章

spring bootspring boot @ConditionalOnxxx相关注解总结

Spring Bootspring.factories

Spring BootSpring MVCSpring有什么区别

Spring BootSpring MVCSpring有什么区别

spring BootSpring中@Controller和@RestController之间的区别

Spring BootSpring MVC 和 Spring 有什么区别?