spring-boot之springboot核心(二)

一:基本配置
1.入口类和@SpringBootApplication
springboot 通常有一个*Applicaiton的入口类,入口类里有一个main方法,这个main方法其实就是一个标准Java应用的入口方法。
在main方法中使用SpringApplication.run(AppStart.class, args);,启动spring boot项目
@SpringBootApplication是一个组合注解
主要组合了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan

也可以注解使用这三个注解完成spring boot项目的启动

注解源码如下:

/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
 * annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.2.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since 1.3.0
	 */
	String[] excludeName() default {};

	/**
	 * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
	 * for a type-safe alternative to String-based package names.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	/**
	 * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 * <p>
	 * Consider creating a special no-op marker class or interface in each package that
	 * serves no purpose other than being referenced by this attribute.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

@SpringBootConfiguration让springboot根据类路径中的jar包依赖,为当前项目进行 自动配置。

如添加了spring-boot-starter-web依赖,那么就会自动转配tomcat和springmvc的依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- <version></version> 由于我们在parent指定了 parent(spring boot) -->
		</dependency>
再如添加了spring-boot-starter-data-jpa依赖,那么spring boot会自动进行jpa相关的依赖。
2.关闭特定的自动配置

2.1.通过@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

@RestController
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@ImportResource({"classpath:test1.xml","classpath:test1.xml"})

3.定制Banner

resources目录下新建banner.txt(自动加载该配置)

.__           .__  .__                               .__       .___
|  |__   ____ |  | |  |   ____   __  _  _____________|  |    __| _/
|  |  \_/ __ \|  | |  |  /  _ \  \ \/ \/ /  _ \_  __ \  |   / __ | 
|   Y  \  ___/|  |_|  |_(  <_> )  \     (  <_> )  | \/  |__/ /_/ | 
|___|  /\___  >____/____/\____/    \/\_/ \____/|__|  |____/\____ | 
     \/     \/                                                  \/
3.1修改banner
http://patorjk.com/software/taag/  设定自定义banner
3.2禁用banner
SpringApplication app= new SpringApplication(AppStart.class);

app.setBannerMode(Banner.Mode.OFF);

app.run(args);

public static void main(String[] args) {
		SpringApplication app= new SpringApplication(AppStart.class);
		app.setBannerMode(Banner.Mode.OFF);
		app.run(args);
	}

4.spring boot的配置文件(*.xml或*.yml)

#修改默认端口
server.port=9090
#重命名项目名称
server.context-path=/hell




#常规属性配置
book.name=java
book.author=fengge

5.starter pom(略过)
6.使用xml配置
spring boot提倡零配置,即无xml配置。但特殊情况下必须引入xml,可以通过@ImportResource注解来加载xml

@ImportResource({"classpath:test1.xml","classpath:test1.xml"})

@RestController
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@ImportResource({"classpath:test1.xml","classpath:test1.xml"})
二:外部配置
spring boot允许使用properties、yml文件或者命令参数作为外部配置
1.命令参数配置
java -jar xx.jar
可以通过命令参数修改tomcat端口
java -jar xx.jar --server.prot=9090
2.常规属性配置

book.name=java

扫描二维码关注公众号,回复: 1026464 查看本文章
#常规属性配置
book.name=java
book.author=fengge
package com.starter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @SpringBootApplication:spring boot项目的核心注解,主要目的是开启自动配置。
 * main方法:主要作用是作为项目的启动入口。
 * @author Hiiso
 *
 */
@RestController
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
//@ImportResource({"classpath:test1.xml","classpath:test1.xml"})
public class AppStart {
	
	@Value("{book.author}")
	private String bookAuthor;
	
	@Value("{book.name}")
	private String bookName;
	
	@RequestMapping("/")
	 String index(){
		return "书的作者:"+bookAuthor+",书的名称:"+bookName;
	}
	
	
	public static void main(String[] args) {
		SpringApplication app= new SpringApplication(AppStart.class);
		app.setBannerMode(Banner.Mode.OFF);
		app.run(args);
	}
	
	
}

3.类型安全的配置(基于properties属性)
3.1类型安全的bean
通过@ConfigurationProperties注解加载properties属性文件的内置配置。通过(prefix="author")制定配置属性的前缀,

通过location={"calsspath:config/author.properties"}(本例不需要制定location)

package com.boot.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="author")
public class AuthorSetting {
	private String name;
	private Long age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Long getAge() {
		return age;
	}
	public void setAge(Long age) {
		this.age = age;
	}
	
}

3.2使用
@Autowired

private AuthorSetting authorSetting;注入该配置文件

package com.starter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boot.config.AuthorSetting;
/**
 * @SpringBootApplication:spring boot项目的核心注解,主要目的是开启自动配置。
 * main方法:主要作用是作为项目的启动入口。
 * @author Hiiso
 *
 */
@RestController
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
//@ImportResource({"classpath:test1.xml","classpath:test1.xml"})
@ComponentScan(basePackages={"com.boot.config"})//指定索要扫描的类文件
public class AppStart {
	
	@Value("{book.author}")
	private String bookAuthor;
	
	@Value("{book.name}")
	private String bookName;
	
	@RequestMapping("/")
	 String index(){
		return "书的作者:"+bookAuthor+",书的名称:"+bookName;
	}
	
	
	@Autowired
	private AuthorSetting authorSetting;
	
	
	@RequestMapping("/p")
	 String index2(){
		return "姓名:"+authorSetting.getName()+",年龄:"+authorSetting.getAge();
	}
	
	public static void main(String[] args) {
		SpringApplication app= new SpringApplication(AppStart.class);
		app.setBannerMode(Banner.Mode.OFF);
		app.run(args);
	}
	
	
}
4.日志配置
4.1默认使用logback作为日志框架
logger.file=../mylogs/log.log

logger.level.org.springframework.web=DEBUG

logger.file=../mylogs/log.log
logger.level.org.springframework.web=DEBUG
5.Profile配置
Profile是spring用来针对不同的环境对不同的配置提供的支持。全局Profile配置使用application-{profile}.properties

5.1 application-dev.properties

#修改默认端口
server.port=8888
#重命名项目名称
server.context-path=/

5.2 application-prodapplication-prod

#修改默认端口
server.port=80
#重命名项目名称
server.context-path=/

5.3 application.properties 通过spring.profiles.active=dev 指定需要使用的配置环境

spring.profiles.active=dev

#常规属性配置
book.name=java
book.author=fengge

#类型安全的bean
author.name=z3
author.age=12

logger.file=../mylogs/log.log
logger.level.org.springframework.web=DEBUG

猜你喜欢

转载自blog.csdn.net/z3133464733/article/details/80355725