最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring 自定義讓@Value被解析到

 更新時間:2021年09月18日 12:26:35   作者:wending-Y  
這篇文章主要介紹了spring 自定義讓@Value被解析到,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

spring 自定義讓@Value解析到

@Value 可以給字段賦值

背景

@Value通常與@PropertySource(value = “db.properties”) 組合使用讀取配置注入?yún)?shù),那如果我們的值是其它存儲,如何才能自動賦值

實(shí)現(xiàn)原理

實(shí)現(xiàn)很簡單

//自動注入此對象 
 @Autowired
    private Environment environment;
    @PostConstruct
    public void init() {
       
       //拿到些對象
        MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
        PropertySourceFactory factory = BeanUtils.instantiateClass(DefaultPropertySourceFactory.class);
        //構(gòu)造pathResource
        PathResource pathResource = new PathResource("/Users/xx/soft/sp.properties");
        try {
            org.springframework.core.env.PropertySource<?> sd = factory.createPropertySource("sd", new EncodedResource(pathResource));
            //設(shè)置值
            propertySources.addFirst(sd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

主要是通過代碼得到PropertySource 這個對象,然后得到environment這個對象,設(shè)置值就可以了

Spring4自定義@Value功能

本文章使用的Spring版本4.3.10.RELEASE

@Value在Spring中,功能非常強(qiáng)大,可以注入一個配置項,可以引用容器中的Bean(調(diào)用其方法),也可以做一些簡單的運(yùn)算

如下的一個簡單demo,

演示@Value的用法

import org.springframework.stereotype.Service; 
/**
 * 測試Bean 
 */
@Service("userService")
public class UserService {
 
 public int count() {
  return 10;
 }
 
 public int max(int size) {
  int count = count();
  return count > size ? count : size;
 }
}
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements InitializingBean {
 
 /**
  * 引用一個配置項
  */
 @Value("${app.port}")
 private int port;
 
 /**
  * 調(diào)用容器的一個bean的方法獲取值
  */
 @Value("#{userService.count()}")
 private int userCount;
 
 /**
  * 調(diào)用容器的一個bean的方法,且傳入一個配置項的值作為參數(shù)
  */
 @Value("#{userService.max(${app.size})}")
 private int max;
 
 /**
  * 簡單的運(yùn)算
  */
 @Value("#{${app.size} <= '12345'.length() ? ${app.size} : '12345'.length()}")
 private int min;
 
 //測試
 public void afterPropertiesSet() throws Exception {
  System.out.println("port : " + port);
  System.out.println("userCount : " + userCount);
  System.out.println("max : " + max);
  System.out.println("min : " + min);
 }
}

app.properties

app.port=9090
app.size=3

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan
@PropertySource("classpath:app.properties")
public class App {
 
    public static void main( String[] args) {
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
     context.close();
    }
}

運(yùn)行,輸出結(jié)果

port : 9090
userCount : 10
max : 10
min : 3

一般的用法就是這樣,用于注入一個值。

那么,能否做到,我給定一個表達(dá)式或者具體的值,它能幫忙計算出表達(dá)式的值呢? 也就是說,實(shí)現(xiàn)一個@Value的功能呢?

方法如下:

import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.expression.StandardBeanExpressionResolver;
public class ValueUtil {
 private static final BeanExpressionResolver resolver = new StandardBeanExpressionResolver();
 
 /**
  * 解析一個表達(dá)式,獲取一個值
  * @param beanFactory
  * @param value 一個固定值或一個表達(dá)式。如果是一個固定值,則直接返回固定值,否則解析一個表達(dá)式,返回解析后的值
  * @return
  */
 public static Object resolveExpression(ConfigurableBeanFactory beanFactory, String value) {
  String resolvedValue = beanFactory.resolveEmbeddedValue(value);
  
  if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) {
   return resolvedValue;
  }
  
  return resolver.evaluate(resolvedValue, new BeanExpressionContext(beanFactory, null));
 }
}

具體使用如下:

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
 
@ComponentScan
@PropertySource("classpath:app.properties")
public class App {
 
    public static void main( String[] args) {
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
     //計算一個具體的值(非表達(dá)式)
     System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "1121"));
     //實(shí)現(xiàn)@Value的功能
     System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "${app.port}"));
     System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{userService.count()}"));
     System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{userService.max(${app.size})}"));
     System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{${app.size} <= '12345'.length() ? ${app.size} : '12345'.length()}"));
     context.close();
    }
}

運(yùn)行輸出如下:

1121
9090
10
10
3

發(fā)現(xiàn)已經(jīng)實(shí)現(xiàn)了@Value的功能

最后,可能有人就有疑問了,這有什么用呢?我直接用@Value難道不好嗎?

對于大部分場景下,的確直接用@Value就可以了。但是,有些特殊的場景,@Value做不了

比如說

我們定義一個注解

@Retention(RUNTIME)
@Target(TYPE)
public @interface Job {
 String cron();
}

這個注解需要一個cron的表達(dá)式,我們的需求是,使用方可以直接用一個cron表達(dá)式,也可以支持引用一個配置項(把值配置到配置文件中)

比如說

@Job(cron = "0 0 12 * * ?")
@Job(cron = "${app.job.cron}")

這種情況@Value就做不到,但是,可以用我上面的解決方案。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java_IO向文件中寫入和讀取內(nèi)容代碼實(shí)例

    java_IO向文件中寫入和讀取內(nèi)容代碼實(shí)例

    這篇文章主要介紹了java_IO向文件中寫入和讀取內(nèi)容,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • 淺談java+內(nèi)存分配及變量存儲位置的區(qū)別

    淺談java+內(nèi)存分配及變量存儲位置的區(qū)別

    下面小編就為大家?guī)硪黄獪\談java+內(nèi)存分配及變量存儲位置的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • SpringBoot異步調(diào)用方法實(shí)現(xiàn)場景代碼實(shí)例

    SpringBoot異步調(diào)用方法實(shí)現(xiàn)場景代碼實(shí)例

    這篇文章主要介紹了SpringBoot異步調(diào)用方法實(shí)現(xiàn)場景代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Spring Security 安全框架應(yīng)用原理解析

    Spring Security 安全框架應(yīng)用原理解析

    這篇文章主要介紹了Spring Security 安全框架應(yīng)用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-07-07
  • 如何將Tomcat容器替換為Jetty容器

    如何將Tomcat容器替換為Jetty容器

    這篇文章主要介紹了如何將Tomcat容器替換為Jetty容器問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • mybatis in查詢傳入String方式

    mybatis in查詢傳入String方式

    這篇文章主要介紹了mybatis in查詢傳入String方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java實(shí)現(xiàn)動態(tài)數(shù)字時鐘

    Java實(shí)現(xiàn)動態(tài)數(shù)字時鐘

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)動態(tài)數(shù)字時鐘,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-12-12
  • 聊聊Spring Boot 如何集成多個 Kafka

    聊聊Spring Boot 如何集成多個 Kafka

    這篇文章主要介紹了Spring Boot 集成多個 Kafka的相關(guān)資料,包括配置文件,生成者和消費(fèi)者配置過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2023-10-10
  • springboot項目不輸出nohup.out日志的解決

    springboot項目不輸出nohup.out日志的解決

    這篇文章主要介紹了springboot項目不輸出nohup.out日志的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Springboot的Mapper中添加新的SQL語句方法詳解

    Springboot的Mapper中添加新的SQL語句方法詳解

    在如今的軟件開發(fā)界,Spring Boot可是非常受歡迎的框架哦,尤其是在微服務(wù)和RESTful API的構(gòu)建上,下面給大家介紹我們?nèi)绾螢镾pring Boot項目中的Mapper添加新的SQL語句吧,感興趣的朋友一起看看吧
    2025-04-04

最新評論

儋州市| 宜宾县| 平山县| 普格县| 正蓝旗| 昌邑市| 原阳县| 诸暨市| 仁怀市| 泸州市| 临桂县| 临武县| 三门县| 巢湖市| 沽源县| 曲水县| 民乐县| 白银市| 永平县| 潢川县| 莱阳市| 陵水| 临泽县| 修武县| 承德市| 临夏县| 江达县| 鄱阳县| 涞源县| 蓝山县| 定兴县| 红安县| 育儿| 邵阳市| 中宁县| 阳信县| 合作市| 天镇县| 垦利县| 霍城县| 舒兰市|