我突然发现当我从非bean类中的方法调用cacheable方法时@Cacheable不起作用。
请在下面找到我的代码并帮助我解决我想念的问题。
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 ***
任何人都可以帮助我吗?
答案 0 :(得分:2)
Spring使用代理来应用AOP,但代理是在构造bean之后创建的。
在@PostConstruct
带注释的方法中,您正在设置对this
的引用,但是那时是bean的未经过代理的实例。你真的需要代理实例。
我还会注意到你的解决方案非常糟糕,不会通过我的QA检查。但那是imho。