无法在 SpringBoot 应用程序中使用 @Value 读取属性

Unable to read properties using @Value in SpringBoot application

所以我有以下结构

@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 。我该如何解决这个问题?

感谢您的帮助!

如果您需要 spring 管理您的 bean,则不能手动实例化 class。

尝试使用 spring 注入

实例化你的 beans
@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

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