所以我有以下结构
@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,则无法手动实例化该类。
尝试使用 spring 注入来实例化你的 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
}
}
你的应用程序属性
com.table1=TABELA_1
# com.table2=
# com.table3=
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)