zoukankan      html  css  js  c++  java
  • 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();
    

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

  • 相关阅读:
    非域账户如何连接SQL Server Analysis Service
    Ranet.UILibrary.OLAP
    给Silverlight项目Ranet.UILibrary.OLAP添加客户端调试功能
    编译及安装QCA类库
    关于软件生态环境
    Windows7中操作mysql数据库
    介绍自己
    VS2008技巧收集
    .NET开发不可错过的25款必备工具
    如何做搜索引擎优化(SEO)
  • 原文地址:https://www.cnblogs.com/wjhmrc/p/13192441.html
Copyright © 2011-2022 走看看