Best way to get data from database inside Thread Class in Spring

无人久伴 提交于 2020-03-04 02:41:07

问题


Currently i am troubling that how to get data from database inside my thread class.

I can't make bean of my thread class because new instance is created of thread on every request.

MyThread.class

class MyThread implements Runnable{
public void run(){
    //How to get Employee data and also data from other tables.??????
}
}    

EmployeeDAO.class

@Component("employeeDAO")
public class EmployeeDAO {

@Cacheable(value = "employeeCache")
public List<Employee> getEmployees() {
     //got data from database
    return employees;
}
}

Is this good to get context and get dao bean from context and use in every my thread class?

Can you suggest or share code how to solve my above problem?


回答1:


I have found one solution from this site .

Is below solution is good or not? If not good then what are disadvantage of solution

Here is what I tried and got success

@Service
public class StaticContextHolder implements ApplicationContextAware {

public static ApplicationContext CONTEXT;

public StaticContextHolder() {
}

public static Object getBean(String s) {
    return CONTEXT.getBean(s);
}

public static <T> T getBean(String s, Class<T> tClass){
    return CONTEXT.getBean(s, tClass);
}

public static <T> T getBean(Class<T> tClass){
    return CONTEXT.getBean(tClass);
}

public static Object getBean(String s, Object... objects){
    return CONTEXT.getBean(s, objects);
}

public static boolean containsBean(String s) {
    return CONTEXT.containsBean(s);
}

@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
    System.out.println("ApplicationContext initialized");
    CONTEXT = arg0;
}   
}    


class MyThread implements Runnable{
public void run(){
     EmployeeDAO employeeDAO = StaticContextHolder.getBean(EmployeeDAO.class);
}
} 


来源:https://stackoverflow.com/questions/28228865/best-way-to-get-data-from-database-inside-thread-class-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!