Best way to get data from database inside Thread C

2019-08-10 08:13发布

问题:

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);
}
}