SpringBoot可以根据项目导入的jar包自动配置相关的Bean,这就涉及到SpringBoot的自动配置原理。
我们通过让SpringBoot配置自定义的User Bean,来演示自动配置的过程。
创建User类
自定义User类,包含4个属性值。这个类是我们希望SpringBoot自动配置的Bean。
@Data
public class User implements ApplicationContextAware {
private String userId;
private String userName;
private String roleId;
private String roleName;
}
创建属性类
定义类UserProperties,这个类用来设置User Bean的默认属性值。这个类有两个功能。
(1)给User Bean的4个属性设置默认值
(2)使用@ConfigurationProperties注解读取Spring配置文件,如果配置文件中设置了值,就用设置的值,否则使用默认值。Spring的配置项以“myuser”为前缀。
@Data
@ConfigurationProperties(prefix = "myuser")
public class UserProperties {
private String userId = "1";
private String userName = "user";
private String roleId = "1";
private String roleName = "admin";
}
设置配置项
在SpringBoot的配置文件application.yml中设置User Bean的属性值,以myuser为前缀。
这里设置了两个,用来测试设置值和默认值是否同时生效。
myuser:
userId: 999
userName: wangwu123
创建自动配置类
创建自动配置类UserAutoConfiguration,这里通过@EnableConfigurationProperties注解加载第二步创建的属性类。使用这个注解的作用是,减少无用Bean的创建,也就是只有UserAutoConfiguration加载为Bean时,才会将UserProperties加载为Bean。
通过方法参数注入UserProperties,获取配置文件设置的属性值和默认属性值。
@EnableConfigurationProperties(UserProperties.class)
public class UserAutoConfiguration {
@Bean
public User user(UserProperties userProperties){
User user = new User();
user.setUserId(userProperties.getUserId());
user.setUserName(userProperties.getUserName());
user.setRoleId(userProperties.getRoleId());
user.setRoleName(userProperties.getRoleName());
return user;
}
}
创建spring.factories
创建spring.factories,文件路径:src/main/resources/META-INF/spring.factories,这个路径不能修改。
在文件中配置我们自定义的自动配置类。
当Spring启动的时候,就会自动读取这个文件,基于创建的自动配置类,设置Bean。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.hello.auto.UserAutoConfiguration
测试
通过Spring上下文对象,打印创建的User Bean,检查application.yml和默认属性值是否设置。
@SpringBootApplication
public class BeanApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(BeanApplication.class, args);
User user = context.getBean(User.class);
System.out.println(user);
}
}
启动项目,控制台打印的userId和userName是Spring配置文件中设置的值,roleId和roleName是默认值。说明Spring自动加载了配置类,并创建了具有指定属性值的Bean。
这个演示的过程就是Spring自动配置的过程,我们经常使用的starter就是基于这个过程进行设置的,如果在配置文件中设置了属性值,就用配置文件设置的值,如果没有设置,就用默认值配置Bean。
比如使用RedisTemplate这个Bean,如果设置了redis的属性“spring.redis.host”,就用设置的地址配置RedisTemplate,如果没有设置,就用默认值localhost。