SpringBoot前置知识02-spring注解发展史

2024-05-23 23:28

本文主要是介绍SpringBoot前置知识02-spring注解发展史,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

springboot前置知识01-spring注解发展史

spring1.x

spring配置只能通过xml配置文件的方式注入bean,需要根据业务分配配置文件,通过import标签关联。

spring1.2版本出现@Transactional注解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="userService" class="com.shaoby.service.UserServiceImpl"></bean>
</beans>
public class UserServiceImpl {
}
public class StartApp {public static void main(String[] args) {ClassPathXmlApplicationContext cp = new ClassPathXmlApplicationContext("applicationContext.xml");Object userService = cp.getBean("userService");System.out.println(userService);}
}

spring2.X

  1. 简化配置,通过compoment-scan和@Component(2.0)、 @Controller(2.5)、@Service(2.5)、 @Repository(2.5)注解实现bean管理
  2. context:annotation-config标签向spring容器中注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor,可以使用@ Resource 、@ PostConstruct、@ PreDestroy等注解
  3. 使用compoment-scan后可以将context:annotation-config移除
  4. 2.X版本没有脱离配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--    <context:annotation-config/>--><context:component-scan base-package="com.shaoby.*" />
</beans>
@Component
public class OtherServiceImpl {
}@Component
public class UserServiceImpl {@Autowiredprivate OtherServiceImpl otherService;
}
public class AppStart {public static void main(String[] args) {ClassPathXmlApplicationContext cp = new ClassPathXmlApplicationContext("applicationContext.xml");for (String beanDefinitionName : cp.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}

spring3.X

spring3.0

  1. 新增@Configuration标记类为配置类,代替applicationContext.xml文件;@Bean注解注入对象,相当于xml中的bean标签;
  2. 无法脱离配置文件,需要借助context即xml中的compoment-scan标签,否则无法识别@Component、@Controller、@Service、@Repository注解;
  3. 提供@ImportResource注解,关联applicationContext配置文件;
  4. 所以就升级成@Configuration注解+applicationContext.xml配合Bean注解使用或者@Configuration注解+applicationContext.xml配合@Component等四个注解使用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.shaoby.*" />
</beans>
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {@Beanpublic OtherServiceImpl otherService(){return new OtherServiceImpl();}
}
@Service
public class UserServiceImpl {
}public class OtherServiceImpl {
}
public class AppStart {public static void main(String[] args) {ApplicationContext ap = new AnnotationConfigApplicationContext(AppConfig.class);for (String beanDefinitionName : ap.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}

spring3.1

1. 新增@ComportScan注解,默认扫描当前包及其子包下是@Component等四个注解修饰的所有类,脱离配置文件;
@Configuration
@ComponentScan("com.shaoby.*")
public class AppConfig {
}
@Component
public class OtherServiceImpl {
}
@Service
public class UserServiceImpl {
}
2. 新增@Import注解
  1. 代替import标签,在配置类中导入其他配置类
@Configuration
public class OtherConfig {@Beanpublic OtherServiceImpl otherService(){return new OtherServiceImpl();}
}@Configuration
@ComponentScan("com.shaoby.*")
@Import({OtherConfig.class})
public class AppConfig {
}
  1. 可以在配置类中直接导入bean
@Configuration
@Import(StudentServiceImpl.class)
public class OtherConfig {@Beanpublic OtherServiceImpl otherService(){return new OtherServiceImpl();}
}public class StudentServiceImpl {
}
  1. 高级用法-动态注入

    @Import注解如果引入了实现ImportSelector注解的类,不会将该类型注入到容器中,而是将selectImports方法返回类型的全类路径字符串的数据注入到容器中

public class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{Logger.class.getName(),Redis.class.getName()};}
}@Configuration
@Import(MyImportSelector.class)
public class JavaConfig {public static void main(String[] args) {ApplicationContext ap = new AnnotationConfigApplicationContext(JavaConfig.class);for (String beanDefinitionName : ap.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
javaConfig
com.shaoby.importtest.Logger
com.shaoby.importtest.Redis

@Import注解如果引入了实现ImportBeanDefinitionRegistrar的类也可以

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {registry.registerBeanDefinition("logger", new RootBeanDefinition(Logger.class));registry.registerBeanDefinition("redis", new RootBeanDefinition(Redis.class));}
}@Configuration
@Import(MyImportBeanDefinitionRegistrar.class)
public class JavaConfig {public static void main(String[] args) {ApplicationContext ap = new AnnotationConfigApplicationContext(JavaConfig.class);for (String beanDefinitionName : ap.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
javaConfig
logger
redis
3. 新增Enabled模块,即EnabledXXX注解,它是结合@Import注解使用的
@Configuration
public class RedisAutoConfiguration {@Beanpublic RedisTemplate redisTemplate(){return new RedisTemplate();}
}public class RedisTemplate {
}

定义开关注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(RedisAutoConfiguration.class)
public @interface EnabledAutoRedisConfiguration {
}
@Configuration
@EnabledAutoRedisConfiguration
public class AppConfig {
}
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
appConfig
com.shaoby.ebabledtest.RedisAutoConfiguration
redisTemplate

注掉@EnabledAutoRedisConfiguration

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
appConfig

spring4.X

新增注解:@Conditional(条件注解),@EventListListener(事件监听),@AliasFor(别名),@CrossOrigin(解决跨域问题)

@Conditional注解

这个注解控制在什么条件下注入bean,这个注解传入一个实现Condition接口的类

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {/*** All {@link Condition} classes that must {@linkplain Condition#matches match}* in order for the component to be registered.*/Class<? extends Condition>[] value();}

在Condition的实现类中可以根据需求判断是否需要注入容器中

@FunctionalInterface
public interface Condition {/*** Determine if the condition matches.* @param context the condition context* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}* or {@link org.springframework.core.type.MethodMetadata method} being checked* @return {@code true} if the condition matches and the component can be registered,* or {@code false} to veto the annotated component's registration*/boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);}

实战

public class JavaConfig {/** 根据MyConditionalOnClass中matches方法返回值判断是否将UsersService注入到容器中*/@Conditional(MyConditionalOnClass.class)@Beanpublic UserService userService(){return new UserService();}public static void main(String[] args) {ApplicationContext ap = new AnnotationConfigApplicationContext(JavaConfig.class);for (String beanDefinitionName : ap.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}public class MyConditionalOnClass implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {/** 根据需求判断是否需要将bean注入到容器中*/boolean userServiceFlag = context.getRegistry().containsBeanDefinition("userService");return userServiceFlag;}
}public class UserService {
}

spring5.X

新增@Indexed(类索引),需要引入依赖。它被标识在@Component注解上,会在编译时会在MATE-INF文件夹下生成spring.components文件夹存储要DI的所有类的全类路径。这样会提高代码启动速度。

<dependency><groupId>org.springframework</groupId><artifactId>spring-context-indexer</artifactId>
</dependency>

总结

在spring的发展中注解的开发已经为SpringBoot的诞生做好了铺垫,其中@EnabledAutoXXXConfiguration、@ConditionalOnXXX、@Import等注解是SpringBoot自动装配原理的核心注解。

这篇关于SpringBoot前置知识02-spring注解发展史的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/996719

相关文章

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

SpringRetry重试机制之@Retryable注解与重试策略详解

《SpringRetry重试机制之@Retryable注解与重试策略详解》本文将详细介绍SpringRetry的重试机制,特别是@Retryable注解的使用及各种重试策略的配置,帮助开发者构建更加健... 目录引言一、SpringRetry基础知识二、启用SpringRetry三、@Retryable注解

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

SpringValidation数据校验之约束注解与分组校验方式

《SpringValidation数据校验之约束注解与分组校验方式》本文将深入探讨SpringValidation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可... 目录引言一、Spring Validation基础架构1.1 jsR-380标准与Spring整合1

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim