springboot笔记_1

第一章  JavaConfig

1. 为什么要使用 Spring Boot

因为spring,springmvc需要大量的配置文件(xml)

还需要配置各种对象,将对象放入容器中才能使用,繁琐

2.springboot就相当于不需要配置文件的spring+springmvc。常用的框架和第三方库都配置好了。

开发效率高

1.1 JavaConfig

 使用java类,上面加上一个@Configuration,这个java类就可以被spring识别为xml文件。可以注册bean。

@Bean:声明对象,把对象注入到容器中。

@Configuration
public class Config {

    /**
     * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
     *       位置:在类的上面
     *
     *  SpringConfig这个类就相当于beans.xml
     */
    
    @Bean(value = "student")
    public Student creatstudent(){
        Student student=new Student("李四",12);
        return student;
    }
}

这样就相当于在xml中对student进行注册,在获取的时候

@Test
    public void beanconfig(){
        ApplicationContext applicationContext=new AnnotationConfigApplicationContext(Config.class);
        Student student = (Student) applicationContext.getBean("creatstudent");
        System.out.println(student);
    }

 通过这个函数获取对象,bean的id值由@bean注解决定,如果没写value值,就使用方法名来获取这个bean,写了就使用value指(student).

@ImportResource 作用导入其他的xml配置文件, 等于 在xml

 <import resources="其他配置文件"/>

@ImportResource(value = "classpath:beans.xml")
public class Config {


<bean id="student" class="com.springboot.pojo.Student">
        <property name="name" value="张三"></property>
        <property name="age" value="21"></property>
</bean>

ApplicationContext applicationContext=new AnnotationConfigApplicationContext(Config.class);
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);//Student(name=张三, age=21)

由于将xml文件引入进来了,所以访问的地址任然是config配置文件,输出的是xml的注入值 

@PropertyResource: 读取properties属性配置文件。 使用属性配置文件可以实现外部化配置 在程序代码之外提供数据。

  1. 在resources目录下,创建properties文件, 使用k=v的格式提供数据

  2. 在PropertyResource 指定properties文件的位置

  3. 使用@Value(value="${key}")

@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages ="com.springboot.pojo" )
public class Config {

@Component(value = "student")
public class Student {
    @Value("${student.name}")
    private String name;
    @Value("${student.age}")
    private int age;
}

student.name="wangwu"
student.age=12

这样就可以将配置文件中的值注入到这个bean中。

解析:首先需要将实体类加上注解,然后这个实体类就归spring管理,然后下面的value值只负责获取文件中的值注入,和直接输入区别不大。${name}就等于配置文件中name的值。

实体类除了自身需要交给spring管理以外,还需要一个包扫描的配置,所以config配置文件中就有@ComponentScan(basePackages ="com.springboot.pojo" ),然后再引入数据文件的路径。

第二 章 Spring Boot

2.1 介绍

SpringBoot是Spring中的一个成员, 可以简化Spring,SpringMVC的使用。 他的核心还是IOC容器。

特点:

  • Create stand-alone Spring applications

    创建spring应用

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

    内嵌的tomcat, jetty , Undertow

  • Provide opinionated 'starter' dependencies to simplify your build configuration

    提供了starter起步依赖,简化应用的配置。

    比如使用MyBatis框架 , 需要在Spring项目中,配置MyBatis的对象 SqlSessionFactory , Dao的代理对象

    在SpringBoot项目中,在pom.xml里面, 加入一个 mybatis-spring-boot-starter依赖

  • Automatically configure Spring and 3rd party libraries whenever possible

    尽可能去配置spring和第三方库。叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中, 开发人员可以直接使用)

  • Provide production-ready features such as metrics, health checks, and externalized configuration

    提供了健康检查, 统计,外部化配置

  • Absolutely no code generation and no requirement for XML configuration

    不用生成代码, 不用使用xml,做配置

2.2 创建Spring Boot项目

2.2.1 第一种方式, 使用Spring提供的初始化器, 就是向导创建SpringBoot应用

使用的地址: https://start.spring.io  

 

 

2.3注解的使用

首先springboot的主启动类上有一个注解

@SpringBootApplication
public class Springboot02Application {

@SpringBootApplication是一个混合注解,包含这样三个重要的注解

  • @SpringBootConfiguration:表明这个类可以当配置文件使用
  • @EnableAutoConfiguration:启用自动配置, 把java对象配置好,注入到spring容器中。例如可以把mybatis的对象创建好,放入到容器中
  • @ComponentScan:扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。
    默认扫描的包: @ComponentScan所在的类所在的包和子包。

    所以说springboot项目的所写代码的包必须放在和主启动类同级,不然无法扫描到。
 

2.4 SpringBoot的配置文件

springboot的配置文件名称是固定的, bootstrap/ application.yml或者.properties两种文件名称和两种后缀

先说一下两种不同命名的区别,:bootstrap是系统级别的一些参数配置,加载优先级比application高,application是应用级别的参数配置

然后在看看两种后缀的区别:

properties后缀: 

#设置端口号
server.port=8082
#设置访问应用上下文路径, contextpath
server.servlet.context-path=/myboot

yml后缀:

server:
  port: 8083
  servlet:
    context-path: /myboot2

整体上区别不大,yml的层次感好点,这种更常用

2.5多环境配置

一般在实际生产中一个程序有多个环境,可以设置多个环境使用

有开发环境, 测试环境, 上线的环境。

每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等

使用多环境配置文件,可以方便的切换不同的配置。

使用方式: 创建多个配置文件, 名称规则: application-环境名称.properties(yml)

创建开发环境的配置文件: application-dev.properties( application-dev.yml )

创建测试者使用的配置: application-test.properties

写一个主要的配置文件,然后两个环境配置。 只需要在application.yml中指定一下就可以

spring:
  profiles:
    active: test

2.6 @ConfigurationProperties

 @ConfigurationProperties: 把配置文件的数据映射为java对象。

在application配置文件中定义

#自定义key=value
school.name=动力节点
school.website=www.bjpowernode.com
school.address=北京的大兴区

然后在类的上面定义

@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {

这样就可以将这个对象注入值并交给容器管理,这里的prefix是前缀

2.7 使用jsp 

springboot不推荐使用jsp,使用模板技术替代jsp。例如thymeleaf模板 

第一步: 加入一个处理jsp的依赖。 负责编译jsp文件

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

如果需要使用servlet, jsp,jstl的功能

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
	<artifactId>javax.servlet.jsp-api</artifactId>
	<version>2.3.1</version>
</dependency>

第二步:创建一个存放jsp的目录

               创建目录,然后在project Strucure-》module-》web-》web Resource Directories-》

第三步:需要在pom文件中指定jsp编译后存放的目录

<resources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

第四步:创建controller

第五步:在application中配置视图解析器

  mvc:
    view:
      prefix: /
      suffix: .jsp

2.8 使用容器

 通过SpringApplication.run(Application.class, args); 返回值获取容器。

 public static void main(String[] args) {

        ConfigurableApplicationContext run = SpringApplication.run(Springboot02Application.class, args);
        Object user = run.getBean("user");
        System.out.println(user);
    }

可以在主启动中将容器获取出来,然后创建出容器中管理的方法

2.9 ComnandLineRunner 接口 , ApplcationRunner接

主启动类中可以实现这些接口,在容器对象创建好之后,自动会执行run方法。可以在这个时候做一些操作

@SpringBootApplication
public class Springboot02Application implements CommandLineRunner {

    @Resource
    private Servicve servicve;

    public static void main(String[] args) {
        System.out.println("容器对象创建");
        ConfigurableApplicationContext run = SpringApplication.run(Springboot02Application.class, args);

    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("容器对象创建之后执行:");
        servicve.commandRuna();
    }
}

这里在容器创建之后执行一些方法。

第三章 Web组件

3.1 拦截器

拦截器是springmvc中的一种对象,能够拦截control请求

首先拦截器是实现HandlerInterceptor接口的这一点没有变

首先看看springmvc中拦截器的使用:

 首先在声明一个类实现HandlerInterceptor接口,然后重写拦截方法

然后直接在mvc文件中绑定一下路径和拦截器就可以了

    <!--    声明拦截器,可以声明多个-->
    <mvc:interceptors>
<!--        第一个-->
        <mvc:interceptor>
<!--            将拦截器和拦截路径绑定-->
            <mvc:mapping path="/**"/>
            <bean class="com.ssm.handler.MyInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

然后就是springboot中使用拦截器

 首先还是需要实现这个接口

public class LoginIntetceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        return false;
    }
}

然后创建一个类实现WebMvcConfigurer接口,重写addInterceptors方法,就可以添加拦截器注册,注意要在这个类中提添加@Configuration,不然springboot无法识别这是一个配置类

@Configuration
public class MyAppConfig implements WebMvcConfigurer {

//   添加拦截器对象

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        创建拦截器对象
        LoginIntetceptor intetceptor = new LoginIntetceptor();
        String path[]={"/user/**"};
        String excludeParh[]={"/user/login"};
        registry.addInterceptor(intetceptor).addPathPatterns(path)
                                            .excludePathPatterns(excludeParh);
    }
}

 3.2  Servlet

在springboot中使用servlet

 首先正常的写一个继承httpservlet的类

然后再配置类中注册,这里需要注意的是,必须将这个servlet注册交给容器管理

@Configuration
public class WebApplication {

    @Bean
    public ServletRegistrationBean servletRegistration(){
//        ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(), "/myservlet");
//        第一种方式,无参数
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new MyServlet());
        bean.setUrlMappings(Arrays.asList(new String[]{"/myservlet", "/aaa"}));
        return bean;
    }
}

3.3 过滤器Filter

在springboot中使用过滤器,有两个步骤:

创建自定义过滤器实现Filter接口

public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("执行了过滤器");
//        用于执行过滤器的转发功能,将请求响应对象传递下去,不然无法传递到控制器。
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

在配置文件中注册过滤器交给容器管理

 @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }

一般使用过滤器是用来解决字符编码的问题,这种时候一般会使用spring框架的过滤器

在springboot中使用CharacterEncodingFilter过滤器解决字符编码问题

 因为这个类本身存在,不需要创建

 @Bean
    public FilterRegistrationBean CharacterEncodingFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
//        创建框架字符过滤器对象
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
//        设置编码
        encodingFilter.setEncoding("utf-8");
//        将这个编码应用为请求和相应对象
        encodingFilter.setForceEncoding(true);
        bean.setFilter(encodingFilter);
        bean.addUrlPatterns("/*");
        return bean;
    }

注册之后需要在配置文件中关闭默认的字符编码设置,不然无法生效

#springboot中默认配置了编码设置,默认是ISO-8859-1
#如果需要使用自己配置的编码,必须关闭这个默认的
server:
  servlet:
    encoding:
      enabled: false

 使用springboot自带的方式设置编码问题

#springboot中默认配置了编码设置,默认是ISO-8859-1
#如果需要使用自己配置的编码,必须关闭这个默认的
server:
  servlet:
    encoding:
      enabled: true
      charset: utf-8
      force: true

 springboot内置了设置的方式,只需要配置文件中这样写就够了。

第四章 ORM 操作 MySQL

4.1使用MyBatis框架操作数据, 在SpringBoot框架集成MyBatis

使用步骤:

  1. mybatis起步依赖 : 完成mybatis对象自动配置, 对象放在容器中

    <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
  2. pom.xml 指定把src/main/java目录中的xml文件包含到classpath中

     <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
            </resources>
  3. 创建实体类Student

  4. 创建Dao接口 StudentDao , 创建一个查询学生的方法(需要使用@Mapper)

  5. 创建Dao接口对应的Mapper文件, xml文件, 写sql语句

  6. 创建Service层对象, 创建StudentService接口和他的实现类。 去dao对象的方法。完成数据库的操作

  7. 创建Controller对象,访问Service。

  8. 写application.properties文件

    配置数据库的连接信息。 

 springboot管理dao层的方式

第一种方式 : @Mapper

@Mapper:放在dao接口的上面, 每个接口都需要使用这个注解。

@Mapper
public interface StudentDao {

    Student selectById(@Param("stuId") Integer id);
}

第二种方式 @MapperScan

@SpringBootApplication
@MapperScan(basePackages = {"com.bjpowernode.dao","com.bjpowernode.mapper"})
public class Application {
}

 在springboot中将xml映射文件和dao接口分开写

 正常准守mapper.xml映射文件的语法,namsespace和sql语句id得一致

然后这个时候一般需要的是mybatis核心配置文件注册方式,还有开启别名驼峰以及日志等等

这种都可以直接在application.yml中配置

mybatis:
  mapper-locations: classpath:**/*.xml
  type-aliases-package: org.springboot.springboot03.pojo
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.2 事务

spring中的事务

1.管理事物得对象:事务管理器

例如:使用Jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager

2.声明式事务:在xml文件中使用注解说明事务控制的内容

控制事务: 隔离级别,传播行为, 超时时间

3.事务的处理方式

spring框架中的springboot

aspectj框架可以在xml配置文件中,声明事务控制的内容

SpringBoot中使用事务: 上面的两种方式都可以。

1)在业务方法的上面加入@Transactional , 加入注解后,方法有事务功能了。

2)明确的在 主启动类的上面 ,加入@EnableTransactionManager

@RequestMapping("/update")
    @Transactional
    public String updateById(){
        Student student = new Student(1, "是搭嘎和接口", 12);
        studentService.updateById(student);
        System.out.println(1/0);
        Student student1 = studentService.select(student.getId());
        return student1.toString();
    }

在整个方法中只要发生了异常,就会直接回滚所有的异常信息·,而且@Transaction注解中有很多的参数可以控制事务。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值