Announcement Announcement Module
Collapse
No announcement yet.
Create bean inside java class Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Create bean inside java class

    Hello just a question is there a way to create instance defined at my applicationContext.xml inside code. Not using spring IOC and declarative method at XML. So if there is any Utils class which can load bean from applicationContext.xml and is accesible for me. So inside any metod something I will have somethikng like this:

    AppContextBean bean = Utilsclass.createBean("name");
    //do some job with bean

  • #2
    Yes, your class can implement the interface ApplicationContextAware in your class.

    If you want a utility class, such as the one you hinting above you can for example use

    Code:
    public class ApplicationContextUtils implements ApplicationContextAware {
    	private static ApplicationContext applicationContext;
    
    	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    		ApplicationContextUtils.applicationContext = applicationContext;
    	}
    
    	public static Object getBean(String name) {
    		return applicationContext.getBean(name);
    	}
    }
    Just a small warning, the code above can potentially be unsafe, if multiple application contexts are running in the same JVM.

    Cheers

    G

    Comment

    Working...
    X