SpringBoot概述


前言

提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:SpringBoot入门篇

一、SpringBoot是什么?

Spring全家桶
通过main方法启动

/**此处的@SpringBootApplication注解相当于@Configuration + @EnableAutoConfiguration + @ComponentScan
*/
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

二、概述

1、Maven的目录结构

默认有resources文件夹,存放资源配置文件。src-main-resources,src-main-java。默认的编译生成的类都在targe文件夹下面。(或者使用更加新颖的Gradle来替代Maven)置

2、spring boot默认的配置文件

必须是,也只能是application.命名的yml文件或者properties文件,且唯一**,取消传统的XML配置

3、application.yml中默认属性。**

数据库连接信息必须是以spring: datasource: 为前缀;多环境配置。该属性可以根据运行环境自动读取不同的配置文件;端口号、请求路径等

4、通过注解与约定其含义来减少配置数量**

Spring中,xml定义的Bean优先于注解定义的Bean,使用注解可以减少Bean在xmL文件配置的麻烦。

4.1spring配置

4.1.1 传统的Spring.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd">
 
    <context:component-scan base-package="com.ssm"/>
 
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" />
 
    <!-- 数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
 
     <!--mybatis的SqlSession的工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:com/ssm/**/*-mapper.xml"/>
    </bean>
 
     <!--告诉mybatis去哪里找mapper.xml文件-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
 
    <!--事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--启动事务-->
    <tx:annotation-driven transaction-manager="transactionManager" order="3"/>
</beans>
4.1.2 基于注解的java类配置方式
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@ComponentScan("com.demo")//启动spring扫描
@PropertySource(value = {"classpath:jdbc.properties"}, ignoreResourceNotFound = true)//找不到配置文件则抛出异常
@EnableTransactionManagement//启动事务
public class SpringConfig {
 
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
 
    //数据源
    @Bean
    public BasicDataSource basicDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8");
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
 
    //session工厂
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(BasicDataSource dataSource) throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
 
        // mapper location
        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(pathResolver.getResources("classpath*:com/demo/**/*-mapper.xml"));
 
        // config file
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.xml"));
        return factoryBean;
    }
 
    //mapper扫描
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.demo.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }
 
    //事务配置
    @Bean
    public PlatformTransactionManager transactionManager(BasicDataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
 
}

4.2SpringMVC配置

4.2.1xml配置方法
步骤一 配置spring-mvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- 启动MVC配置 -->
    <mvc:annotation-driven/>
 
    <!-- 静态资源 -->
    <mvc:resources mapping="/static/**" location="/static/">
        <mvc:cache-control max-age="3600" cache-public="true"/>
    </mvc:resources>
    
    <!-- 启动mvc的自动扫描。Spring.xml可以不用扫描 -->
    <context:component-scan base-package="com.demo"/>
 
    
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    </bean>     
 
    <!--用来支持文件上传的multipart处理器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--todo 可以通过配置参数控制上传文件的内容和大小-->
    </bean>
</beans>
步骤二 配置web.xml
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:mvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
4.2.2java注解方式
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
@Configuration
@EnableWebMvc//启动springMVC注解驱动 等价于xml 配置中的<mvc:annotation-driven/>
@ComponentScan("com.demo")//扫描创建控制器类
public class WebMvcConfig extends WebMvcConfigurerAdapter {
 
    @Bean//定义试图解析器
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
 
    //静态资源配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("/static/js")
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
    }
 
    /*静态资源交给默认的servlet
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }*/
 
    //文件上传组件
    @Bean
    public MultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }
}

再配个启动类(相当于web.xml中配置ContextLoadListener) 继承了AbstractAnnotationConfigDispatcherServletInitializer的AppInitalizer的作用就类似web.xml中的ContextLoadListener,并且会在web项目运行初始化被自动发现并加载,这就是java config的魅力所在了,不管在哪里声明了配置了,只要继承了AbstractAnnotationConfigDispatcherServletInitializer,它就可以被自动加载。

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};//非SpringMVC上下文配置类,不需要就return null
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebMvcConfig.class};//SpringMVC上下文配置类
    }
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};//dispatcher映射路径,一个string的列表,这里处理所有请求
    }
//相当于web.xml中的
//<servlet-mapping>
//    <servlet-name>mvc</servlet-name>
//    <url-pattern>/</url-pattern>
//</servlet-mapping>
}

RootConfig,不需要的话在上面 WebAppInitializer 的 getRootConfigClasses() 里直接return null即可

可以参考官方文档:

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#spring-web

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan(basePackages="com.ssm",excludeFilters={
        @ComponentScan.Filter(type= FilterType.ANNOTATION,value=EnableWebMvc.class)
})
public class RootConfig {
//RootConfig.class的内容如下,它可以放在和AppInitializer同个目录下,主要用来配置spring的bean,这里只关注web项目的实现,所以暂时没有具体内容
}

除此之外,还有关于shiro的配置,详见 https://blog.youkuaiyun.com/weixin_41612354/article/details/81736678?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=1328575.12154.16146692452626485&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值