springboot3.x入门系列【4】spring注解使用

一、简介

在Spring Boot开发中,利用Spring提供的注解可以极大地简化应用配置和开发流程。这些注解不仅帮助我们以声明式的方式构建和管理Bean,还支持自动化配置,使得开发者能够轻松实现依赖注入、条件化Bean创建以及其他高级功能。通过合理使用这些注解,Spring Boot应用能够实现更高的灵活性和可维护性。

二、spring 注解

1. @ConditionalOnProperty

在Spring框架中,@ConditionalOnProperty 注解是一个条件化配置注解,它根据指定属性是否存在以及其值是否符合要求来决定是否创建某个Bean。这个注解通常用在Spring Boot的自动配置类或者Bean的定义上。

下面是 @ConditionalOnProperty 注解的一些关键点:

  • value: 指定需要检查的属性的名称。可以是一个字符串数组,表示多个属性名称。
  • havingValue: 指定当属性的值符合这个值时,条件才为真。如果属性的值是一个集合,那么只要包含这个值,条件就为真。
  • matchIfMissing: 当属性不存在时是否视为条件满足。默认为 false,即如果属性不存在,条件不满足。
@ConditionalOnProperty(
        value = {"auth.system.code"},
        havingValue = "isc"
)
public class ConfigLoadProcessor implements EnvironmentPostProcessor, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(ConfigLoadProcessor.class);

    private static final String CONFIG_PROPERTIES = "config.properties";


    @Override
    public int getOrder() {
        return -1;
    }

    private void collectLogMessage(String configPath, String installationPath) {
        LogMessage logMessage = LogMessage.initialize().
                setConfigPath(configPath).setConfigLoaderLastModifiedTime(PropertiesUtils.acquireFileLastModifiedTime(configPath)).
                setConfigLoaderMd5(PropertiesUtils.calculateMd5(configPath)).
                setInstallationPath(installationPath).setInstallationLoaderLastModifiedTime(PropertiesUtils.acquireFileLastModifiedTime(installationPath)).
                setInstallationLoaderMd5(PropertiesUtils.calculateMd5(installationPath));
        LogMessageHolder.setLogMessage(logMessage);
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        logger.info("loading config.properties & installation.properties");
        // 加载 config.properties 和 installation.properties
        Properties properties = BootstrapListener.getConfigAndInstallationProperties();
        environment.getPropertySources().addFirst(new PropertiesPropertySource(CONFIG_PROPERTIES, properties));
    }
}

2. @ConditionalOnExpression

在 Spring Framework 中,@ConditionalOnExpression 是一个条件注解,它允许基于 SpEL(Spring Expression Language)表达式的计算结果来有条件地注册 Bean。如果表达式计算为 true,则相关的配置类或 Bean 将被注册到 Spring 容器中;如果为 false,则不会注册。

1) 等值式

 /**
     * token认证拦截器
     */
    @Configuration
    @ConditionalOnClass(IdentityAuthInterceptor.class)
    @ConditionalOnExpression("!'${spring.application.name}'.equals('sUpms')")
    protected static class IdentityAuthHandlerWebConfig implements WebMvcConfigurer {
        @Autowired
        BeanFactory beanFactory;
        //swagger忽略路径
        public final List<String> excludedList = new ArrayList<>(Arrays.asList(CommonConstants.SWAGGER_IGNORE_PATH));

        @Value("#{'${x86.security.ignored.url:/api/*}'.split(',')}")
        public String[] ignoredUrls;

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //不拦截的地址
            excludedList.addAll(Arrays.stream(ignoredUrls).toList());
            registry.addInterceptor(this.beanFactory.getBean(IdentityAuthInterceptor.class))
                    .order(Ordered.LOWEST_PRECEDENCE - 1)
                    //排除的请求
                    .excludePathPatterns(excludedList)
                    //拦截所有请求
                    .addPathPatterns("/**");
            WebMvcConfigurer.super.addInterceptors(registry);

        }

        @Bean
        IdentityAuthInterceptor identityAuthInterceptor() {
            return new IdentityAuthInterceptor();
        }

    }

2)开启式

 /**
     * 菜单权限拦截器
     */
    @Configuration
    @ConditionalOnClass(IdentityAuthInterceptor.class)
    @ConditionalOnExpression("${x86.menu.privilege.enabled:false}==true")
    protected static class MenuPrivilegeHandlerWebConfig implements WebMvcConfigurer {

        @Override
        public void addInterceptors(InterceptorRegistry registry) {

            registry.addInterceptor(new MenuPrivilegeInterceptor())
                    .order(Ordered.LOWEST_PRECEDENCE - 2)
                    //拦截所有请求
                    .addPathPatterns("/**");
            WebMvcConfigurer.super.addInterceptors(registry);

        }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值