如何在静态区域中使用instence变量,如果类在Spring Boot中自动连线


/* 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;
}
}

试试这个。

1.构造函数注入

public class Address{
private static Employee employee;
@Autowired
public Address(Employee employee){
Address.employee= employee;
}
public static void display(){
employee.name;
}
}

2.Post 构造

public class Address{
private static Employee employee;
@Autowired
private Employee employeeI;
@PostConstruct
public void init() {
Address.employee= employeeI;
}
public static void display(){
employee.name;
}
}

在静态块中使用实例变量是不可能的,您可能需要更改逻辑以合并相同的变量。

相关内容

最新更新