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

spring 自定義讓@Value被解析到

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

spring 自定義讓@Value解析到

@Value 可以給字段賦值

背景

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

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

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

//自動(dòng)注入此對(duì)象 
 @Autowired
    private Environment environment;
    @PostConstruct
    public void init() {
       
       //拿到些對(duì)象
        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 這個(gè)對(duì)象,然后得到environment這個(gè)對(duì)象,設(shè)置值就可以了

Spring4自定義@Value功能

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

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

如下的一個(gè)簡(jiǎn)單demo,

演示@Value的用法

import org.springframework.stereotype.Service; 
/**
 * 測(cè)試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 {
 
 /**
  * 引用一個(gè)配置項(xiàng)
  */
 @Value("${app.port}")
 private int port;
 
 /**
  * 調(diào)用容器的一個(gè)bean的方法獲取值
  */
 @Value("#{userService.count()}")
 private int userCount;
 
 /**
  * 調(diào)用容器的一個(gè)bean的方法,且傳入一個(gè)配置項(xiàng)的值作為參數(shù)
  */
 @Value("#{userService.max(${app.size})}")
 private int max;
 
 /**
  * 簡(jiǎn)單的運(yùn)算
  */
 @Value("#{${app.size} <= '12345'.length() ? ${app.size} : '12345'.length()}")
 private int min;
 
 //測(cè)試
 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

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

那么,能否做到,我給定一個(gè)表達(dá)式或者具體的值,它能幫忙計(jì)算出表達(dá)式的值呢? 也就是說,實(shí)現(xiàn)一個(gè)@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();
 
 /**
  * 解析一個(gè)表達(dá)式,獲取一個(gè)值
  * @param beanFactory
  * @param value 一個(gè)固定值或一個(gè)表達(dá)式。如果是一個(gè)固定值,則直接返回固定值,否則解析一個(gè)表達(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);
     //計(jì)算一個(gè)具體的值(非表達(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難道不好嗎?

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

比如說

我們定義一個(gè)注解

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

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

比如說

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

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

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

相關(guān)文章

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

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

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

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

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

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

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

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

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

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

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

    mybatis in查詢傳入String方式

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

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

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

    聊聊Spring Boot 如何集成多個(gè) Kafka

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

    springboot項(xiàng)目不輸出nohup.out日志的解決

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

    Springboot的Mapper中添加新的SQL語(yǔ)句方法詳解

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

最新評(píng)論

长治县| 鹤庆县| 文成县| 龙山县| 峨山| 宁都县| 麟游县| 穆棱市| 闸北区| 衡东县| 武胜县| 游戏| 和林格尔县| 泌阳县| 公主岭市| 五台县| 南通市| 喀喇沁旗| 靖西县| 马关县| 灌南县| 葵青区| 遵义市| 嵩明县| 广汉市| 衡阳县| 乐平市| 昌图县| 象山县| 连南| 麻阳| 简阳市| 定州市| 洛川县| 左权县| 长岭县| 江陵县| 教育| 赤水市| 英吉沙县| 桃园县|