Search code examples
javaspringhibernatemanaged-bean

Accessing DAO Service methods from non managedbeans


I am using Spring 3 and Hibernate 4

How can I use the following in a non ManagedBean

@Inject 
EmployeeService employeeService 

Or if I would want to access DAO method I have to make that a ManagedBean as

@Named("mymanagedbean")
@ViewAccessScoped 

I have a few Converter class and in order to access DAO service methods I had to use that as ManagedBean even though they are not ManagedBeans.

What is the best approach to call DAO service methods?

Thanks


Solution

  • You will need to implement the Spring interface ApplicationContextAware and then set the ApplicationContext. Then you need provide static methods to get the bean instance.

    public class SpringApplicationContext implements ApplicationContextAware {
    
    private static ApplicationContext CONTEXT;
    
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        CONTEXT = context;
    }
        public static Object getBean(String beanName) { ...}
        public static <T> T getBean(Class<T> arg0) {...}
    

    Then in your non-managed bean you can call SpringApplicationContext.getBean method by passing in EmployeeService.class as the argument or the bean name as the argument.