spring boot内置tomcat,可以直接通过javac命令来运行,不需要打war包。
spirng boot入口自然是注解@SpringBootApplication,启动类上如果有该注解,表明该项目为spring boot项目,则在启动的时候会进行自动配置。
点击@SpringBootApplication进去会发现该注解有三个注解组成,
@SpringBootApplication = @Configuration + @EnableAutoConfaguration + @ComponentScan。
@Configuration:标注该类是一个JavaConfig配置类
@EnableAutoConfaguration:表示会自动为依赖的jar包进行配置,比如项目添加了spring-boot-starter-web依赖包,则该注解会自动为项目提供tomcat和spring MVC的配置。
@ComponentScan:spring会自动对入口类同级及下级包所有的类进行bean管理。
如果想关闭某个依赖的自动化配置,通过exclude属性设置。
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
这样在项目启动的时候就不会对DataSourceAutoConfiguration进行自动配置。
springBoot目的是减少配置文件,支持无配置文件,但有些项目需要配置文件,所以springBoot也支持xml配置文件的引入。
比如在入口类增加注解:@ImportResource({"classpath:some-context.xml","classpath:another-context.xml"})
以redis自动配置为例子。
1、首先注解 @EnableAutoConfaguration 一直往里点,最终会遇到一个类AutoConfigurationImportSelector,这个类有个方法会扫描所有依赖jar的类路径下的META-INF/spring.factories文件。
2、在文件内可以找到一个key为org.springframework.boot.autoconfigure.EnableAutoConfiguration的列表。
3、在这个列表中可以找到org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration。 这个类就是redis自动配置类。
@Configuration
@ConditionalOnClass({JedisConnection.class, RedisOperations.class, Jedis.class})
@EnableConfigurationProperties({RedisProperties.class})//加载属性文件
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}
@Configuration
protected static class RedisConfiguration {
protected RedisConfiguration() {
}
@Bean//自动实例化redisTemplate到spring容器
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean({StringRedisTemplate.class})
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
}
原文:https://www.cnblogs.com/yanhui007/p/12595648.html