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

  • prcek
    started a topic Create bean inside java class

    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

  • Goran
    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

    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.



    Leave a comment: