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”)

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