Access Spring beans in Runnable thread

I need to access Spring beans ( featureServiceand uxService) in my Runnable Thread below, but I get a value nullfor applicationContext, so I could not get Spring beans inside Runnable. I am wondering if it is possible to access Spring beans inside runnable or not? if not, suggest me an alternative approach.

I use Spring 4.0.6andJava 8

@Component
public class UserMenuUpdateTask implements Runnable, Serializable, ApplicationContextAware {


    private static final long    serialVersionUID = 3336518785505658027L;

    List<User>                   userNamesList;

    FeatureService               featureService;

    UXService uxService;

    private ApplicationContext   applicationContext;

    public UserMegaMenuUpdateTask() {}

    public UserMegaMenuUpdateTask(List<User> userNamesList) {
        this.userNamesList = userNamesList;
    }

    @Override
    public void run() {
        try {
            for (User user : userNamesList) {

                    featureService = (FeatureService) applicationContext.getBean("featureService");
                    uxService = (UxService) applicationContext.getBean("uxService");                    
                //.........
            }
        } catch (BaseApplicationException ex) {
            throw new BaseApplicationException(ex);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
}

I call runnable as below

ExecutorService es = Executors.newCachedThreadPool();
es.execute(new UserMenuUpdateTask(activeUsers));
+4
source share
3 answers

Spring ThreadLocal applicationContext, ExecutorService , no beans / beanContext beans.

.

+1

ApplicationContextAware - , Spring, beans, Spring (). UserMenuUpdateTask , Spring .

runnable / (.. UserMenuUpdateTask ), Spring ( XML ) Spring - ExecutorService.execute().

UserMenuUpdateTask, ApplicationContextAware (, Spring), UserMenuUpdateTask, ExecutorService.

+1

ApplicationContextAware , spring. UserMenuUpdateTask (activeUsers) spring , , applicationContext.

Write the constructor without parameters, set the scope for the prototype and get this object from spring, set activeUsers in the next line, and it should work. Or install the application by hand after creating the object.

I would also recommend that you change these lines

    for (User user : userNamesList) {

        featureService = (FeatureService) applicationContext.getBean("featureService");
        uxService = (UxService) applicationContext.getBean("uxService");                    
            //.........
        }

to

    featureService = (FeatureService) applicationContext.getBean("featureService");
    uxService = (UxService) applicationContext.getBean("uxService");      

    for (User user : userNamesList) {
        //.........
    }
0
source

All Articles