探索Spring Boot


探索Spring Boot(一)

最出的起点

###通过Maven来创建Spring Boot

####pom.xml

添加父依赖,和Web模块:spring-boot-starter-web

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

配置Spring Boot的启动类

@SpringBootApplication
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class,args);
    }
}

Druid数据库连接池

###1.增加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.6</version>
</dependency>

1.5 SSM纯XML配置数据源例子(使用c3p0演示)

db.properties

jdbc.username=root
jdbc.password=mysql123
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false
<!--数据源-->

<!--指定配置文件的位置-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置c3p0-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
</bean>

不优雅!!!!!!!!!!1

2.使用纯Java 的配置(相比xml配置优雅)

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {

    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driver}")
    String driver;
    @Value("${jdbc.username}")
    String userName;
    @Value("${jdbc.password}")
    String passWord;


    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        dataSource.setUrl(url);

        return dataSource;
    }
}

jdbc.properties

jdbc.username=root
jdbc.password=mysql123
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false

3.更优雅的配置方式

创建application.properties(Spring Boot的默认命名,约定大于配置)

jdbc.username=root
jdbc.password=mysql123
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false

新建JdbcProperties.java

若不想手动添加getter setter方法 可以使用lombok的@Data注解(需要引入该依赖,并且在idea中添加配件)

@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcProperties {
    String url;
    String driver;
    String userName;
    String passWord;
}

修改JdbcConfig.java

package com.an.study.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcProperties.driver);
        dataSource.setUsername(jdbcProperties.userName);
        dataSource.setPassword(jdbcProperties.passWord);
        dataSource.setUrl(jdbcProperties.url);

        return dataSource;
    }
}

4.最最最优雅的方式

1.将application.properties中的jdbc配置写为约定的形式

jdbc.username=root
jdbc.password=mysql123
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false

2.修改JdbcConfig.java

@Bean注解的作用是将DataSource注册为一个Java Bean 让Spring管理

@ConfigurationProperties 的作用是引入application.properties中前缀为jdbc的属性。也就是说会自动调用对象的set方法,所以使用该种方式要保证名称一致。

@Configuration
public class JdbcConfig {
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }
}

###5.还能更优雅吗? 可以

properties ——> yaml

删除application.properties

新建application.yml

server:
  port: 10086

jdbc:
  username: root
  password: mysql123
  driverClassName: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false

保留4中的JdbcConfig.java(不需要@ConfigurationProperties类,不需要db.properties配置文件,不需要@Value注解,也不需要手动设置值,约定俗成下的配置就是这么简单)

###6.重新思考一下上面的东西优雅吗? 不优雅!

我们甚至不想要JdbcConfig.java 因为这个文件不太好看。它参杂到我们的项目中,不是很优雅!

那么?其实Spring Boot已经帮我们写好了这写数据源的配置类。我们只需要在配置文件中修改配置的属性就可以用了!眼不见心不烦,配置类确实以某种方式存在,但是我们看不到 NICE! 详情请寻找Spring Boot 自动配置与源码相关文章了解。

也就是说只需要导入Spring Boot支持的数据库连接池并且在 yml配置文件中声明一下就可以了。

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: mysql123

HikariCP 秒天秒地的连接池?

数据库驱动 和连接池

spring-boot-starter-jdbc 中默认带有HikariCP

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: mysql123

##配置文件相关

application.properties和application.yml同时存在,取两个配置文件的并集。

如果有冲突取application.properties的配置

注解讲解

@Bean

@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名

相当于

<bean id="dataSource" class="XXXXXX"/>

###@EnableConfigurationProperties

注解的作用是@ConfigurationProperties注解生效。如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的。

###@SpringBootApplication

@SpringBootApplication注解,它包括三个注解:

@Configuration:表示将该类作用springboot配置文件类。

@EnableAutoConfiguration:表示程序启动时,自动加载springboot默认的配置。

@ComponentScan:表示程序启动是,自动扫描当前包及子包下所有类。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{.........} 

@ComponentScan

该注解默认从 标有该注解的 包开始扫描也就是从 SpringBoot启动类(标有@SpringBootApplication 注解的类)开始扫描。

If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

@SpringBootConfiguration

这就是一个配置类@Configuration的注解 ,Spring Boot为了和Configuration区分所以只是名字上不一样

Application should only ever include <em>one</em> {@code @SpringBootConfiguration} and most idiomatic Spring Boot applications will inherit it from
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

@ConfigurationProperties

注解主要用来把properties配置文件(在Spring Boot中默认是application.properties)转化为bean

@Configuration

@Configuration也可以注解一个配置类,不一样的是它需要为每个属性再次声明绑定的字段,稍微复杂.如上面的使用纯java配置

@EnableAutoConfiguration

Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined. 

Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration.

###Spring中的常用注解

@Service用于标注业务层组件

@Controller用于标注控制层组件(如struts中的action)

@Repository用于标注数据访问组件,即DAO组件

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

##注意

###关于@EnableAutoConfiguration

若缺少此注解可能会产生**org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.**错误

自动配置初探

自动配置 = 提前写好类 + 根据特定的条件生效

生效的条件:1.引入了相关的依赖 (Spring boot 启动器 spring-boot-starter-xxx)

​ 2.你自己没有配置Bean

Log

yaml配置文件

logging:
  level: 
    com.an.study: debug

使用方法一

private static final Logger logger = LoggerFactory.getLogger(XXX.class)   //XXX.class 代表当前类名

使用方法二

使用lombok+idea插件

直接在类名上添加注解@Slf4j @Log4j @Log4j2 ..即可使用 log.info(“information”) ….

Spring MVC Interceptor

1.新建一个类实现HandlerInterceptor接口

public class MyInterceptor implements HandlerInterceptor{}

2.添加java配置类 将MyInterceptor注册

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");;
    }
}

文章作者: Bxan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bxan !
  目录