为什么从非bean类的方法调用可缓存方法时@Cacheable不起作用 [英] Why @Cacheable not working when calling cacheable method from method of non bean class
问题描述
我突然发现,当我从非bean类内部的方法调用可缓存方法时,@ Cacheable无法正常工作.
I have suddently found that @Cacheable not worked when i call cacheable method from method inside not bean class.
请在我的代码下面找到并帮助我解决问题或错过的事情.
Please find below my code and help me what is issue or something i miss.
EmployeeDAO.java
@Component("employeeDAO")
public class EmployeeDAO {
private static EmployeeDAO staticEmployeeDAO;
public static EmployeeDAO getInstance(){
return staticEmployeeDAO;
}
@PostConstruct
void initStatic(){
staticEmployeeDAO = this;
}
@Cacheable(value = "employeeCache")
public List<Employee> getEmployees() {
Random random = new Random();
int randomid = random.nextInt(9999);
System.out.println("*** Creating a list of employees and returning the list ***");
List<Employee> employees = new ArrayList<Employee>(5);
employees.add(new Employee(randomid, "Ben", "Architect"));
employees.add(new Employee(randomid + 1, "Harley", "Programmer"));
employees.add(new Employee(randomid + 2, "Peter", "BusinessAnalyst"));
employees.add(new Employee(randomid + 3, "Sasi", "Manager"));
employees.add(new Employee(randomid + 4, "Abhi", "Designer"));
return employees;
}
MyThread.java
class MyThread{
public void run(){
//How to get Employee data. ?????
}
}
UtilityClass.java
public class UtilityClass {
public static void getEmployee(){
EmployeeDAO.getInstance().getEmployees();
}
}
Main.java
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAO");
System.out.println("1'st call");
dao.getEmployees();
System.out.println("2'nd call");
dao.getEmployees();
System.out.println("Call cache method using utility class");
System.out.println("1'st call on utilityclass");
UtilityClass.getEmployee();
System.out.println("2'nd call on utilityclass");
UtilityClass.getEmployee();
}
}
输出:
1'st call
*** Creating a list of employees and returning the list ***
2'nd call
Call cache method using utility class
1'st call on utilityclass
*** Creating a list of employees and returning the list ***
2'nd call on utilityclass
*** Creating a list of employees and returning the list ***
有人可以帮助我吗?
推荐答案
Spring使用代理来应用AOP,但是代理是在构造bean之后创建的.
Spring uses proxies to apply AOP, however proxies are created after a bean has been constructed.
在带有@PostConstruct
注释的方法中,您正在设置对this
的引用,但是此时是Bean的未代理实例.您确实需要代理实例.
In your @PostConstruct
annotated method you are setting a reference to this
however at that moment that is the unproxied instance of the bean. You really need the proxied instance.
我还要指出,您的解决方案是非常糟糕的解决方案,不会通过我的质量检查.但这是恕我直言.
I would also note that your solution is imho a very bad one and wouldn't pass my QA check. but that is imho.
这篇关于为什么从非bean类的方法调用可缓存方法时@Cacheable不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!