需求:读取application.properties的自定义属性值用于代码中,之后在需要修改数值的时候就直接修改配置文件即可



两种方式



第一种,直接使用注解@org.springframework.beans.factory.annotation.Value获取值

在这里插入图片描述

@org.springframework.beans.factory.annotation.Value("${neo.uri}")
    private String uri;

    @org.springframework.beans.factory.annotation.Value("${neo.username}")
    private String username;

    @org.springframework.beans.factory.annotation.Value("${neo.password}")
    private String password;

@ConditionalOnProperty



第二种方式,将需要使用的属性值封装成一个实体类

步骤如下

第一步:在配置文件application.properties中加入自定义属性值,例如:

gulimall.thread.coreSize=1;gulimall.thread.maxSize=1;gulimall.thread.keepAliveTime=60


第二步:新建配置类ThreadPoolConfigProperties,加入注解@ConfigurationProperties(prefix=“gulimall.thread”)、@Component,属性包含自定义属性,例如:

在这里插入图片描述

第三步:如果第二步中,配置类ThreadPoolConfigProperties未加@component注解,那么就需要在使用的类中加上@EnableConfigurationProperties(ThreadPoolConfigProperties.class)来指定读取配置类是谁,如下图:

在这里插入图片描述

第四步:自动注入并使用

在这里插入图片描述

在spring boot中有时候需要控制配置类是否生效,可以使用@ConditionalOnProperty注解来控制@Configuration是否生效.

@Configuration
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
public class FilterConfig {
	//prefix为配置文件中的前缀,
	//name为配置的名字
	//havingValue是与配置的值对比值,当两个值相同返回true,配置类生效.
    @Bean
    public FilterRegistrationBean getFilterRegistration() {
        FilterRegistrationBean filterRegistration  = new FilterRegistrationBean(new LoginFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }
}

配置文件中的代码:

filter.loginFilter=true



版权声明:本文为weixin_42707397原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42707397/article/details/120846348