I am following this tutorial online to the letter. http://www.tutorialspoint.com/spring/spring_bean_life_cycle.htm
But I get the errors when using Eclipse when I get to
You should use AbstractApplicationContext instead of ApplicationContext according to the spring documentation http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-nature
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Boot {
public static void main(final String[] args) throws Exception {
AbstractApplicationContext ctx
= new ClassPathXmlApplicationContext(new String []{"beans.xml"});
// add a shutdown hook for the above context...
ctx.registerShutdownHook();
// app runs here...
// main method exits, hook is called prior to the app shutting down...
}
}
I also got the same issue. I solved it using this way.
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
HelloWorld obj =(HelloWorld)context.getBean("helloWorld");
obj.getMessage();
((AbstractApplicationContext) context).registerShutdownHook();
}
Here is the code that worked for me.
package arjun;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();
Triangle triangle=(Triangle) context.getBean("triangle");
triangle.draw();
}
}
//use this line,
((AbstractApplicationContext) ctx).registerShutdownHook();
Here's an updated solution:
import org.springframework.context.support.AbstractApplicationContext;
((AbstractApplicationContext) appContext).registerShutdownHook();
For the error it seems that context is a object of ApplicationContext, whereas in tutorial it should be an object of AbstractApplicationContext
I am just guessing that you wrote this
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");//error here
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}