开发者

How to access spring managed beans from service layer

I am not able to get spring bean in the service la开发者_开发知识库yer(ServiceContext.getBean("beanName")). I am able to get the bean in the servlet though. What am I doing wrong in the following class?

package com.ekaplus.presentation.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ServiceContext implements ApplicationContextAware{

    private static ApplicationContext applicationContext;       

    @SuppressWarnings("static-access")
    public  void setApplicationContext(ApplicationContext ctx)throws BeansException {
        this.applicationContext=ctx;        
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String beanName)
    {
        return applicationContext.getBean(beanName);
    }

}


try do it without static access. Smt like this (only for test)

class ServiceContext {
    public static Object getBean(final String beanName){
        return new ApplicationContextAware(){
            Object res;
            @Override
            public void setApplicationContext(ApplicationContext applicationContext)
                    throws BeansException {
                res = applicationContext.getBean(beanName);
            }

            Object getBean(){
                return res;
            }

        }.getBean();
    }
}


Is your Servicecontext managed by Spring. Looks like it's not. And if it is not managed by Spring it cannot inject ApplicationContext in your Servicecontext object.

If you can tell what you are trying to achieve than it will be easier to suggest. Especially what is the role of ServiceContext? Cannot the beans be wired automatically?


There were some libs problem in ear and web-inf lib. It is working now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜