Java 如果类在spring boot中自动连接,如何在静态区域使用instence变量
无法在静态块中使用实例变量,您可能必须更改逻辑以合并相同的实例变量。尝试此操作 1.构造函数注入Java 如果类在spring boot中自动连接,如何在静态区域使用instence变量,java,spring,spring-boot,spring-data-jpa,Java,Spring,Spring Boot,Spring Data Jpa,无法在静态块中使用实例变量,您可能必须更改逻辑以合并相同的实例变量。尝试此操作 1.构造函数注入 /* This condition will ariese when we will read the values from property file and there a change to use this value in static area */ @Component public class Employee{ String name="radhe";
/* This condition will ariese when we will read the values from property file and there a change to use this value in static area */
@Component
public class Employee{
String name="radhe";
}
public class Address{
@Autowired
Employee employee;
public static void display(){
employee.name;
}
}
2.后期施工
public class Address{
private static Employee employee;
@Autowired
public Address(Employee employee){
Address.employee= employee;
}
public static void display(){
employee.name;
}
}
嗨,毗瑟奴,我恐怕你根本不清楚你想解决什么问题。不能从静态上下文中引用变量。但这只是一个Java属性,与Spring无关。请添加您想要实现的描述,我们可能会提供帮助。嗨,Jenschauder,我有一个类Employee,其中有一些变量,我想使用@ConfigurationProperties从属性文件读取值,并且我必须在静态区域使用threse变量。如果我在Employee类中使用静态变量,那么我无法从属性文件中读取值。为什么这个部分必须是静态的?例如,您为什么不使用
Employee
springbean,并在当前使用静态变量的地方注入它呢。另外:显示“雇员”名称而不显示“雇员”的完整定义的语义是什么?不,先生,雇员只是一个类名。例如,类名可以是任何东西,变量可能有其他名称,但概念是,如何在静态区域使用实例变量请再次阅读我的问题,应用逻辑后我得到空值我有一个类Employee,因为有一些变量,我想使用@ConfigurationProperties从属性文件读取值,我必须在静态区域使用threse变量。若我在Employee类中接受静态变量,那个么我就不能从属性文件中读取值
public class Address{
private static Employee employee;
@Autowired
private Employee employeeI;
@PostConstruct
public void init() {
Address.employee= employeeI;
}
public static void display(){
employee.name;
}
}