Spring教程
从上下文中获取Bean的示例:
package spring.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); MyBean mybean1 = (MyBean) context.getBean("mybean"); MyBean mybean2 = context.getBean("mybean", MyBean.class); System.out.print(mybean1 == mybean2); //output: true } }
第一种方式:只指定bean名称,不指定类型,结果需要强制类型转换
第二种方式:同时指定bean名称和类名称,结果不需要强制类型转换