溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Springboot如何在有參構(gòu)造方法類中使用@Value注解取值

發(fā)布時(shí)間:2020-06-28 16:57:32 來(lái)源:億速云 閱讀:1393 作者:清晨 欄目:開(kāi)發(fā)技術(shù)

小編給大家分享一下Springboot如何在有參構(gòu)造方法類中使用@Value注解取值,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!

我們?cè)赟pringboot中經(jīng)常使用@Value注解來(lái)獲取配置文件中的值,像下面這樣

@Component
class A {
   @Value("${user.value}")
   private String configValue;
   
   public void test() {
      System.out.println(configValue);
   }
}

但有時(shí)我們需要這個(gè)類擁有一個(gè)有參的構(gòu)造方法,比如

@Component
class A {
   @Value("${user.value}")
   private String configValue;

   private String s;

   public A(String s) {
      this.s = s;
   }
   public void test() {
      System.out.println(s);
      System.out.println(configValue);
   }
}

要使@Value生效,必須把Bean交給Spring進(jìn)行管理,而不能使用new去實(shí)例化對(duì)象,否則@Value取值為NULL。我們一般使用@Autowired都是默認(rèn)注入無(wú)參的構(gòu)造方法,要想注入有參的構(gòu)造方法,我們需要構(gòu)建Config類:

@Configuration
public class AConfig {
  @Bean(name="abc")
  DataOpration abcA() {
    return new A("abc");
  }
}

然后創(chuàng)建SpringUtil類

@Component
public class SpringUtil implements ApplicationContextAware {

  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if(SpringUtil.applicationContext == null) {
      SpringUtil.applicationContext = applicationContext;
    }
  }

  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  //通過(guò)name獲取 Bean.
  public static Object getBean(String name){
    return getApplicationContext().getBean(name);
  }
}

在調(diào)用時(shí),只需要獲取到對(duì)應(yīng)的Bean

A a = (A) SpringUtil.getBean("abc");
a.test();

就可以同時(shí)獲取到配置文件中的值和傳入的參數(shù)。

看完了這篇文章,相信你對(duì)Springboot如何在有參構(gòu)造方法類中使用@Value注解取值有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI