【问题标题】:Unable to read properties using @Value in SpringBoot application无法在 Spring Boot 应用程序中使用 @Value 读取属性
【发布时间】:2021-09-01 20:24:32
【问题描述】:

所以我有以下结构

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

感谢您的帮助!

【问题讨论】:

  • ` public printTableName(){ System.out.println(tableName); }` 这个函数的返回类型是什么?我认为无效的声明

标签: java spring spring-boot spring-mvc spring-data


【解决方案1】:

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

尝试使用弹簧注入实例化您的 bean

@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
    
    }

}

您的应用程序.properties

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2021-12-07
    • 2017-06-26
    • 2016-12-23
    • 2017-07-03
    • 2014-01-07
    • 2018-02-19
    相关资源
    最近更新 更多