Springboot如何在有参构造方法类中使用@Value注解取值

发布时间:2020-06-28 16:57:32 作者:清晨
来源:亿速云 阅读:1373

小编给大家分享一下Springboot如何在有参构造方法类中使用@Value注解取值,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!

我们在Springboot中经常使用@Value注解来获取配置文件中的值,像下面这样

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

但有时我们需要这个类拥有一个有参的构造方法,比如

@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进行管理,而不能使用new去实例化对象,否则@Value取值为NULL。我们一般使用@Autowired都是默认注入无参的构造方法,要想注入有参的构造方法,我们需要构建Config类:

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

然后创建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;
  }

  //通过name获取 Bean.
  public static Object getBean(String name){
    return getApplicationContext().getBean(name);
  }
}

在调用时,只需要获取到对应的Bean

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

就可以同时获取到配置文件中的值和传入的参数。

看完了这篇文章,相信你对Springboot如何在有参构造方法类中使用@Value注解取值有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. Springboot中@Value如何解决获取值为空的问题
  2. Springboot中@Value的使用详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot value ue

上一篇:sklearn的predict_proba是什么

下一篇:JavaScript语言的新特性

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》