user1935987 user1935987 - 1 year ago 79
Java Question

Spring use @Autowired field not in @Component

I Have a case in my app, that i need to use the object

AccountsDao accountsDao

public class Account {

private AccountsDao accountsDao;

without putting an attribute
class(and without any other method to mark it as a spring bean).

The app is huge, and there is an objective reason why
must not be a Spring Bean and must be initialized manually.

I also know that this is a single case, and the common structure is OK.

Is there a way to do that?

Answer Source


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class SpringUtils implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;

    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
        // TODO Auto-generated method stub
        SpringUtils.beanFactory = arg0;

    public static <T> T getBean(Class<T> clz) throws BeansException {
        T result = (T) beanFactory.getBean(clz);
        return result;



AccountsDao accountsDao = SpringUtils.getBean(AccountsDao.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download