SpringBoot入门到精通

springboot目前是主流的框架, 基于ssm框架的封装,更加便利我们程序员开发, 所以总结一下,让小白的你们可以迅速成长

为什么使用SpringBoot

简化 SSM开发

SpringBoot特性

1. 嵌入式Servlet容器,无需打包
2. starts自动依赖于版本控制
3. 大量的自动配置,简化开发
4. 无需配置xml,无代码生成,开箱即用
5. 生产环境应用监控
6. 云计算集成

SpringBoot基本配置

1. SpringBoot基本流程
2. SpringBoot Pom文件结构
3. SpringBoot启动项解析
4. SpringBoot 配置
5. SpringBoot 日志
6. SpringBoot嵌入式Servlet
7. SpringBoot数据访问.

1. SpringBoot基本流程

搭建SpringBoot框架总共有3种方式
第一种方式是在官网上, 通过这个地址,选择自己所需的功能

https://start.spring.io/
在这里插入图片描述

第二种方式是idea帮我们自动创建好的在这里插入图片描述
第三种方式是我们自己手动创建
1 添加Pom文件

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

2 添加启动项

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

}

3 添加测试Controller,Helloworld

@RestController
public class HelloController {
@RequestMapping("hello")
    public String hello(){
        return "hello world";
    }
}

2. SpringBoot Pom文件结构

  1. 父管理所有依赖的版本,帮我们解决版本冲突问题
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

为什么帮助我们解决了版本冲突问题?

点进去看

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-dependencies</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath>../../spring-boot-dependencies</relativePath>
	</parent>

在这里插入图片描述
2. 自动依赖组件

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starters</artifactId>
		<version>1.5.9.RELEASE</version>
	</parent>

在这里插入图片描述
3 web依赖
在这里插入图片描述

这次知道为什么使用springboot的时候只需要简单更改一下pom文件就可以,并且还不用担心版本号问题, 如果是web项目, 我们需要引入很多依赖,但是springboot已经帮我们做成了 以整体,直接引入就可以

SpringBoot启动项解析

我们从注解启动开始解析,

启动
@SpringBootApplication


// 配置文件类, 作用域@Configuration效果一样
@SpringBootConfiguration
// 自动导入配置
@EnableAutoConfiguration


点进入@EnableAutoConfiguration

@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)

点进入@AutoConfigurationPackage, @Import的作用类似于我们配置注入到容器组件 一样

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

点进入AutoConfigurationPackages.Registrar.class

作用是加载com.judy.springboot.learn下所有组件注入到容器中., 这就是为什么我们要让启动项在最上面, 包含我们所有包的原因
在这里插入图片描述

@AutoConfigurationPackage的作用扫描所有包

@Import(EnableAutoConfigurationImportSelector.class)

public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector 
  public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,BeanFactoryAware, EnvironmentAware, Ordered {
	@Override
	public String[] selectImports(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return NO_IMPORTS;
		}
		try {
			AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
					.loadMetadata(this.beanClassLoader);
			AnnotationAttributes attributes = getAttributes(annotationMetadata);
           //**重点突出**点进入getCandidateConfigurations
			List<String> configurations = getCandidateConfigurations(annotationMetadata,
					attributes);
			configurations = removeDuplicates(configurations);
			configurations = sort(configurations, autoConfigurationMetadata);
			Set<String> exclusions = getExclusions(annotationMetadata, attributes);
			checkExcludedClasses(configurations, exclusions);
			configurations.removeAll(exclusions);
			configurations = filter(configurations, autoConfigurationMetadata);
			fireAutoConfigurationImportEvents(configurations, exclusions);
			return configurations.toArray(new String[configurations.size()]);
		}
		catch (IOException ex) {
			throw new IllegalStateException(ex);
		}
	}
}
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
			AnnotationAttributes attributes) {
			**// 进入loadFactoryNames方法**
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
				getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
		Assert.notEmpty(configurations,
				"No auto configuration classes found in META-INF/spring.factories. If you "
						+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}
	public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
	
	public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
		String factoryClassName = factoryClass.getName();
		try {
			Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
			List<String> result = new ArrayList<String>();
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
				String factoryClassNames = properties.getProperty(factoryClassName);
				result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
			}
			return result;
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
					"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
	}

进入META-INF/spring.factories 下面 , 会把他们自动装入到容器中
在这里插入图片描述

SpringBoot 配置文件

SpringBoot配置文件有两种方式

1 Properties和yml文件

以前配置文件和现在配置文件写法对比

yml写法
server:
   port: 8081
 
 
xml
<server>
    <port>8081</prot>
</server>

配置文件语法

k:(空格)V
空格缩进表示层级关系
大小写敏感

值获取的方式
1 @Value($(“XXXX”))

导入一个值
   @Value("${person.name}")
    private String name;

2 @PropertySource(value={“classpath:person.properties”})

加载指定文件的值, 不一定是application.Properties或者是application.yml文件
@PropertySource(value = {"classpath:person.properties"}) //加载指定配置文件

3 ImportSource(locations={“classpath:bean.xml”})

让Spring配置文件生效,例如bean.xml文件

4 @Configuration @Bean 方法名就是id

@Configuration
public class ConfigBean {
    @Bean
    public PersionService persionService(){
     return  new PersionService();
    }
}

5 @ConfigurationProperties(prefix=“person”)

从全局配置文件中获取

在这里插入图片描述

激活指定的profile

Spring.profile.active = dev 单个配置文件

块状配置

server:
  port: 8081
spring:
  profiles:
    active: test

---
server:
  port: 8082
spring:
  profiles: prod

---
server:
  port: 8083
spring:
  profiles: test
 

命令行
JVM参数形式

SpringBoot日志

springBoot使用的而是SL4J和Logback

Springboot如何整合日志

  1. 将系统中其他日志框架先排除出去
  2. 用中间包来替换原有的日志框架
  3. 导入slf4j其他实现

springboot把其他日志都替换为slf4j
在这里插入图片描述

数据访问层

JDBC

         <dependency>
		     	<groupId>mysql</groupId>
		    	<artifactId>mysql-connector-java</artifactId>
		    	<scope>runtime</scope>
	    </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
 @Autowired
    JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/query")
    public Map<String,Object> map(){
        List<Map<String,Object>>list= jdbcTemplate.queryForList("select * FROM department");
        return list.get(0);
    }

Mybatis

	<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>

在这里插入图片描述

如果每个类单独配置则使用@mapper, 如果想全部都使用则在启动项使用@MapperScan(value=“com.judy.data.mapper”)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章