简体   繁体   中英

How to instantiate generic spring bean?

I'm trying to create a generic class that will help me reduce boilerplate code. I'm using Spring 3 (MVC) and Hibernate 4 for this.

Class looks like this:

@Repository("AutoComplete")
public class AutoComplete<T extends Serializable> implements IAutoComplete {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> entity;

    public AutoComplete(Class<T> entity) {
        this.setEntity(entity);
    }

    @Transactional(readOnly=true)
    public List<String> getAllFTS(String searchTerm) {
        Session session = sessionFactory.getCurrentSession();
        return null;
    }

    public Class<T> getEntity() {
        return entity;
    }

    public void setEntity(Class<T> entity) {
        this.entity = entity;
    }

}

I'm instantiating bean like this:

IAutoComplete place = new AutoComplete<Place>(Place.class);
place.getAllFTS("something");

If I run the code, I'm getting "no default constructor found" exception. If I add a default constructor I'm getting null pointer exception at this line:

Session session = sessionFactory.getCurrentSession();

Why is this and how can I solve this problem? I'm guessing the problem is because bean is not getting instantiated by Spring itself so it can't autowire fields. I would like to instantiate bean myself but still have it spring managed if possible.

Make Sure you have added <context:component-scan base-package='package name'> in your xml bean definition file.

As @Repository is stereotype, Spring container will do classpath scanning , add it's bean definition and injects it's dependencies.

Later you can get handle of bean from ApplicationContext with bean name (AutoComplete).

Spring container will instantiate this bean for you,in that case,sessionFactory will be injected. You instantiate this bean by your own code: new AutoComplete(),of course sessionFactory is null.

Never instantiate classes with fields which has @Autowired annotation. If you do that field will result in null. What you should do is that you should get a reference to ApplicationContext of Spring (you can do this by implementing ApplicationContextAware interface) and use the following code in your AutoComplete class's default constructor.

public AutoComplete() {
    sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
}

One of the major practice while using Spring is eliminating instantition of objects by ourselves. We should specify everything in spring configuration so that Spring will instantiate objects for us when we need. But in your case with the Generic approach you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM