栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133530.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号