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();
}
}
Output :
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 ***
Can any one help me ?
Spring uses proxies to apply AOP, however proxies are created after a bean has been constructed.
In your
@PostConstruct
annotated method you are setting a reference tothis
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.