SYSTEM
底层注解
src/content/notes/system/底层注解.md 底层注解
SpringBoot
@SpringBootApplication:启动注解,实现 SpringBoot 的自动部署
- 参数 scanBasePackages:可以指定扫描范围
- 默认扫描当前引导类所在包及其子包
假如所在包为 com.example.springbootenable,扫描配置包 com.example.config 的信息,三种解决办法:
-
使用 @ComponentScan 扫描 com.example.config 包
-
使用 @Import 注解加载类,这些类都会被 Spring 创建并放入 ioc 容器,默认组件的名字就是全类名
-
对 @Import 注解进行封装
//1.@ComponentScan("com.example.config")
//2.@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);
}
}
UserConfig:
@Configuration
public class UserConfig {
@Bean
public User user() {
return new User();
}
}
EnableUser 注解类:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(UserConfig.class)//@Import注解实现Bean的动态加载
public @interface EnableUser {
}
Configuration
@Configuration:设置当前类为 SpringBoot 的配置类
- proxyBeanMethods = true:Full 全模式,每个 @Bean 方法被调用多少次返回的组件都是单实例的,默认值,类组件之间有依赖关系,方法会被调用得到之前单实例组件
- proxyBeanMethods = false:Lite 轻量级模式,每个 @Bean 方法被调用多少次返回的组件都是新创建的,类组件之间无依赖关系用 Lite 模式加速容器启动过程
@Configuration(proxyBeanMethods = true)
public class MyConfig {
@Bean //给容器中添加组件。以方法名作为组件的 id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public User user(){
User user = new User("zhangsan", 18);
return user;
}
}
Condition
条件注解
Condition 是 Spring4.0 后引入的条件化配置接口,通过实现 Condition 接口可以完成有条件的加载相应的 Bean
注解:@Conditional
作用:条件装配,满足 Conditional 指定的条件则进行组件注入,加上方法或者类上,作用范围不同
使用:@Conditional 配合 Condition 的实现类(ClassCondition)进行使用
ConditionContext 类API:
| 方法 | 说明 |
|---|---|
| ConfigurableListableBeanFactory getBeanFactory() | 获取到 IOC 使用的 beanfactory |
| ClassLoader getClassLoader() | 获取类加载器 |
| Environment getEnvironment() | 获取当前环境信息 |
| BeanDefinitionRegistry getRegistry() | 获取到 bean 定义的注册类 |
-
ClassCondition:
public class ClassCondition implements Condition { /** * context 上下文对象。用于获取环境,IOC容器,ClassLoader对象 * metadata 注解元对象。 可以用于获取注解定义的属性值 */ @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); } }
自定义注解
将类的判断定义为动态的,判断哪个字节码文件存在可以动态指定
-
自定义条件注解类
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ClassCondition.class) public @interface ConditionOnClass { String[] value(); } -
ClassCondition
public class ClassCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) { //需求:通过注解属性值value指定坐标后创建bean Map<String, Object> map = metadata.getAnnotationAttributes (ConditionOnClass.class.getName()); //map = {value={属性值}} //获取所有的 String[] value = (String[]) map.get("value"); boolean flag = true; try { for (String className : value) { Class<?> cls = Class.forName(className); } } catch (Exception e) { flag = false; } return flag; } } -
UserConfig
@Configuration public class UserConfig { @Bean @ConditionOnClass("com.alibaba.fastjson.JSON")//JSON加载了才注册 User 到容器 public User user(){ return new User(); } } -
测试 User 对象的创建
常用注解
SpringBoot 提供的常用条件注解:
@ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化 Bean
@Configuration
public class UserConfig {
@Bean
@ConditionalOnProperty(name = "it", havingValue = "seazean")
public User user() {
return new User();
}
}
it=seazean
@ConditionalOnClass:判断环境中是否有对应类文件才初始化 Bean
@ConditionalOnMissingClass:判断环境中是否有对应类文件才初始化 Bean
@ConditionalOnMissingBean:判断环境中没有对应Bean才初始化 Bean
ImportRes
使用 bean.xml 文件生成配置 bean,如果需要继续复用 bean.xml,@ImportResource 导入配置文件即可
@ImportResource("classpath:beans.xml")
public class MyConfig {
//...
}
<beans ...>
<bean id="haha" class="com.lun.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.lun.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
Properties
@ConfigurationProperties:读取到 properties 文件中的内容,并且封装到 JavaBean 中
配置文件:
mycar.brand=BYD
mycar.price=100000
JavaBean 类:
@Component //导入到容器内
@ConfigurationProperties(prefix = "mycar")//代表配置文件的前缀
public class Car {
private String brand;
private Integer price;
}