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

相关文章

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关