Return to Snippet

Revision: 4799
at January 21, 2008 12:16 by narkisr


Updated Code
//The interface:

public interface AppContainer {

    <T> T getIns(Class<T> clazz);

    Object getInstanceSkipCast(Class clazz);

}


//The implementation:

import static org.apache.commons.lang.StringUtils.uncapitalize;

public class DefaultAppContainer implements AppContainer {

    private ApplicationContext factory;

    public DefaultAppContainer() {
        factory = new ClassPathXmlApplicationContext("spring/application.xml");
    }

    public <T> T getIns(Class<T> clazz) {// this should work for 90% of the casses
        return (T) factory.getBean(uncapitalize(clazz.getSimpleName()));
    }

    public Object getInstanceSkipCast(Class clazz) {
        return factory.getBean(uncapitalize(clazz.getSimpleName()));
    }


}

Revision: 4798
at January 21, 2008 12:16 by narkisr


Updated Code
The interface:

public interface AppContainer {

    <T> T getIns(Class<T> clazz);

    Object getInstanceSkipCast(Class clazz);

}


The implementation:

import static org.apache.commons.lang.StringUtils.uncapitalize;

public class DefaultAppContainer implements AppContainer {

    private ApplicationContext factory;

    public DefaultAppContainer() {
        factory = new ClassPathXmlApplicationContext("spring/application.xml");
    }

    public <T> T getIns(Class<T> clazz) {// this should work for 90% of the casses
        return (T) factory.getBean(uncapitalize(clazz.getSimpleName()));
    }

    public Object getInstanceSkipCast(Class clazz) {
        return factory.getBean(uncapitalize(clazz.getSimpleName()));
    }


}

Revision: 4797
at January 21, 2008 12:08 by narkisr


Initial Code
public interface AppContainer {

    <T> T getIns(Class<T> clazz);

    Object getInstanceSkipCast(Class clazz);

}

public class DefaultAppContainer implements AppContainer {

    private ApplicationContext factory;

    public DefaultAppContainer() {
        factory = new ClassPathXmlApplicationContext("spring/application.xml");
    }

    public <T> T getIns(Class<T> clazz) {// this should work for 90% of the casses
        return (T) factory.getBean(uncapitalize(clazz.getSimpleName()));
    }

    public Object getInstanceSkipCast(Class clazz) {
        return factory.getBean(uncapitalize(clazz.getSimpleName()));
    }


}

Initial URL

                                

Initial Description
A very simple way of getting bean instances from Spring context without casting returned object, the assumption is that the bean id's are matching the classes names.

Initial Title
A simple solution for "castless" spring application context

Initial Tags
java

Initial Language
Java