user1935987 user1935987 - 4 months ago 17
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 {

@Autowired
private AccountsDao accountsDao;


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

The app is huge, and there is an objective reason why
Account
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

add SpringUtils.java

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

@Component
public class SpringUtils implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    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;
    }

}

use

AccountsDao accountsDao = SpringUtils.getBean(AccountsDao.class);