SpringBoot高级--原理分析
@Conditional要配和Condition的实现类(ClassCondition)进行使用
-
ClassCondition
public class ClassCondition implements Condition { /** * * @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象 * @param metadata 注解元对象。 可以用于获取注解定义的属性值 * @return */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { //1.需求: 导入Jedis坐标后创建Bean //思路:判断redis.clients.jedis.Jedis.class文件是否存在 boolean flag = true; try { Class<?> cls = Class.forName("redis.clients.jedis.Jedis"); } catch (ClassNotFoundException e) { flag = false; } return flag; } }
UserConfig
@Configuration public class UserConfig { @Bean @Conditional(ClassCondition.class) public User user(){ return new User(); } }
测试
@SpringBootApplication public class SpringbootConditionApplication { public static void main(String[] args) { //启动SpringBoot的应用,返回Spring的IOC容器 ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args); Object user = context.getBean("user"); System.out.println(user); } }
需求:将类的判断定义为动态的。判断哪个字节码文件存在可以动态指定。
自定义ClassCondition类实现Condition接口, 用来判断注解属性值value
package com.itheima.springbootcondition.condtion; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; public class ClassCondition implements Condition { /** * * @param context 上下文对象。用于获取环境,IOC容器,ClassLoader对象 * @param metadata 注解元对象。 可以用于获取注解定义的属性值 * @return */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { //2.需求: 导入通过注解属性值value指定坐标后创建Bean //获取注解属性值 value Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName()); //System.out.println(map); String[] value = (String[]) map.get("value"); boolean flag = true; try { for (String className : value) { Class<?> cls = Class.forName(className); } } catch (ClassNotFoundException e) { flag = false; } return flag; } }
import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ClassCondition.class) public @interface ConditionOnClass { String[] value(); }
@Configuration public class UserConfig { @Bean //@Conditional(ClassCondition.class) @ConditionOnClass("com.alibaba.fastjson.JSON") public User user(){ return new User(); } @Bean @ConditionalOnProperty(name = "itcast",havingValue = "itheima") public User user2(){ return new User(); } }
测试User对象的创建
@SpringBootApplication public class SpringbootConditionApplication { public static void main(String[] args) { //启动SpringBoot的应用,返回Spring的IOC容器 ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args); Object user = context.getBean("user"); System.out.println(user); } }
查看条件注解源码
SpringBoot 提供的常用条件注解:
ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化Bean
ConditionalOnClass:判断环境中是否有对应字节码文件才初始化Bean
排除Tomcat
pom文件中的排除依赖效果
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--排除tomcat依赖--> <exclusions> <exclusion> <artifactId>spring-boot-starter-tomcat</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency> <!--引入jetty的依赖--> <dependency> <artifactId>spring-boot-starter-jetty</artifactId> <groupId>org.springframework.boot</groupId> </dependency>
演示代码:
/** * @ComponentScan 扫描范围:当前引导类所在包及其子包 * * com.itheima.springbootenable * com.itheima.config * //1.使用@ComponentScan扫描com.itheima.config包 * //2.可以使用@Import注解,加载类。这些类都会被Spring创建,并放入IOC容器 * //3.可以对Import注解进行封装。 */ //@ComponentScan("com.itheima.config") //@Import(UserConfig.class) @EnableUser @SpringBootApplication public class SpringbootEnableApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args); //获取Bean Object user = context.getBean("user"); System.out.println(user); } }
pom中引入springboot-enable-other
<dependency> <groupId>com.itheima</groupId> <artifactId>springboot-enable-other</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
springboot-enable-other工程
UserConfig
@Configuration public class UserConfig { @Bean public User user() { return new User(); } }
EnableUser注解类
import org.springframework.context.annotation.Import; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(UserConfig.class) public @interface EnableUser { }
三种解决方案:
1.使用@ComponentScan扫描com.itheima.config包
2.可以使用@Import注解,加载类。这些类都会被Spring创建,并放入IOC容器
@Enable 底层依赖于@Import注解导入一些类,使用@Import导入的类会被Spring加载到IOC容器中。而@Import提供4中用法:
①导入Bean
②导入配置类
③导入 ImportSelector 实现类。一般用于加载配置文件中的类
④导入 ImportBeanDefinitionRegistrar 实现类。
-
导入Bean @Import(User.class)
-
导入配置类 @Import(UserConfig.class)
-
导入 ImportSelector 实现类 @Import(MyImportSelector.class)
MyImportSelector
public class MyImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"com.itheima.domain.User", "com.itheima.domain.Role"}; } }
导入 ImportBeanDefinitionRegistrar 实现类。@Import({MyImportBeanDefinitionRegistrar.class})
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition(); registry.registerBeanDefinition("user", beanDefinition); } }
SpringbootEnableApplication测试代码
/* Import4种用法: 1. 导入Bean 2. 导入配置类 3. 导入ImportSelector的实现类。 4. 导入ImportBeanDefinitionRegistrar实现类 */ //@Import(User.class) //@Import(UserConfig.class) //@Import(MyImportSelector.class) //@Import({MyImportBeanDefinitionRegistrar.class}) @SpringBootApplication public class SpringbootEnableApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args); /*//获取Bean Object user = context.getBean("user"); System.out.println(user);*/ /*User user = context.getBean(User.class); System.out.println(user); Role role = context.getBean(Role.class); System.out.println(role);*/ /* Object user = context.getBean("user"); System.out.println(user);*/ Map<String, User> map = context.getBeansOfType(User.class); System.out.println(map); } }
@EnableAutoConfiguration中使用的是第三种方式:@Import(AutoConfigurationImportSelector.class)
-
-
配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当 SpringBoot 应用启动时,会自动加载这些配置类,初始化Bean
-
需求:自定义redis-starter。要求当导入redis坐标时,SpringBoot自动创建Jedis的Bean。
①创建 redis-spring-boot-autoconfigure 模块
②创建 redis-spring-boot-starter 模块,依赖 redis-spring-boot-autoconfigure的模块
③在 redis-spring-boot-autoconfigure 模块中初始化 Jedis 的 Bean。并定义META-INF/spring.factories 文件
④在测试模块中引入自定义的 redis-starter 依赖,测试获取 Jedis 的Bean,操作 redis。
pom文件中引入redis-spring-boot-autoconfigure
<!--引入configure-->
<dependency>
<groupId>com.itheima</groupId>
<artifactId>redis-spring-boot-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
@ConfigurationProperties(prefix = "redis") public class RedisProperties { private String host = "localhost"; private int port = 6379; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
创建RedisAutoConfiguration自动配置类
@Configuration @EnableConfigurationProperties(RedisProperties.class) public class RedisAutoConfiguration { /** * 提供Jedis的bean */ @Bean public Jedis jedis(RedisProperties redisProperties) { return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
注意:”\ “是换行使用的
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.itheima.redis.config.RedisAutoConfiguration
在springboot-enable工程中引入自定义的redis的starter
<!--自定义的redis的starter--> <dependency> <groupId>com.itheima</groupId> <artifactId>redis-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
在SpringbootEnableApplication启动类中测试
Jedis jedis = context.getBean(Jedis.class); System.out.println(jedis);
redis.port=6666
使用注解完成有条件加载配置类
@Configuration @EnableConfigurationProperties(RedisProperties.class) @ConditionalOnClass(Jedis.class) public class RedisAutoConfiguration { /** * 提供Jedis的bean */ @Bean @ConditionalOnMissingBean(name = "jedis") public Jedis jedis(RedisProperties redisProperties) { System.out.println("RedisAutoConfiguration...."); return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
Java中的事件监听机制定义了以下几个角色:
①事件:Event,继承 java.util.EventObject 类的对象
②事件源:Source ,任意对象Object
③监听器:Listener,实现 java.util.EventListener 接口 的对象
SpringBoot 在项目启动时,会对几个监听器进行回调,我们可以实现这些监听器接口,在项目启动时完成一些操作。
-
ApplicationContextInitializer、
-
SpringApplicationRunListener、
-
CommandLineRunner、
-
ApplicationRunner
自定义监听器的启动时机:MyApplicationRunner和MyCommandLineRunner都是当项目启动后执行,使用@Component放入容器即可使用
/** * 当项目启动后执行run方法。 */ @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("ApplicationRunner...run"); System.out.println(Arrays.asList(args.getSourceArgs())); } }
MyCommandLineRunner
@Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunner...run"); System.out.println(Arrays.asList(args)); } }
MyApplicationContextInitializer的使用要在resource文件夹下添加META-INF/spring.factories
org.springframework.context.ApplicationContextInitializer=com.itheima.springbootlistener.listener.MyApplicationContextInitializer
@Component public class MyApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("ApplicationContextInitializer....initialize"); } }
public class MySpringApplicationRunListener implements SpringApplicationRunListener { public MySpringApplicationRunListener(SpringApplication application, String[] args) { } @Override public void starting() { System.out.println("starting...项目启动中"); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { System.out.println("environmentPrepared...环境对象开始准备"); } @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.println("contextPrepared...上下文对象开始准备"); } @Override public void contextLoaded(ConfigurableApplicationContext context) { System.out.println("contextLoaded...上下文对象开始加载"); } @Override public void started(ConfigurableApplicationContext context) { System.out.println("started...上下文对象加载完成"); } @Override public void running(ConfigurableApplicationContext context) { System.out.println("running...项目启动完成,开始运行"); } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { System.out.println("failed...项目启动失败"); } }
-
-
判断是否是Web环境
-
-
-
执行监听器
-
准备环境
-
打印banner:可以resource下粘贴自定义的banner
-
refreshContext(context);
执行refreshContext方法后才真正创建Bean