无法在 SpringBoot 应用程序中使用 @Value 读取属性 [英] Unable to read properties using @Value in SpringBoot application

查看:58
本文介绍了无法在 SpringBoot 应用程序中使用 @Value 读取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下结构

@Component 
@RequiredArgsConstructor
ClassA{
    ClassB b = new ClassB();
    b.printTableName(); 
}

@Component
@RequiredArgsConstructor
ClassB{
  @Value("${com.table}")
  private String tableName;
  
  public printTableName(){
    System.out.println(tableName);
  }
}


printTableName 函数总是打印 null ,这个函数中的 tableName 总是 null .我该如何解决这个问题?


The printTableName function always prints null , the tableName in this function is always null . How do I go about fixing this ?

感谢您的帮助!

推荐答案

如果你需要 spring 管理你的 bean,你不能手动实例化类.

You cannot instance the class manually if you need the spring manage your beans.

尝试使用 spring 注入来实例化你的 bean

Try instance your beans with spring injects

@Component
public class ClassB {

    @Value("${com.table1}")
    private String valueRequiredOnProperties;

    @Value("${com.table2:#{null}}")
    private String valueNullByDefaultIfNotInformedOnProperties;
    
    @Value("${com.table3:table_default}")
    private String valueByDefaultTableIfNotInformedOnProperties;
    
    
    public void printTableName(){
        System.out.println(valueRequiredOnProperties);
        System.out.println(valueNullByDefaultIfNotInformedOnProperties);
        System.out.println(valueByDefaultTableIfNotInformedOnProperties);
    }

}



@Component
public class ClassA { // you need call this class in controllers, configurations or others ways to spring manager the instances

    // it's necessary indicate to spring manage the instance of beans
    @Autowired
    private ClassB classBManagedBySpring;

    public void callPrintClassB(){
    
        ClassB classB = new ClassB();
        
        classBManagedBySpring.printTableName(); // this will work
        classB.printTableName(); // this will not work
    
    }

}

您的 application.properties

your application.properties

com.table1=TABELA_1
# com.table2=
# com.table3=

这篇关于无法在 SpringBoot 应用程序中使用 @Value 读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆