控制反转(IOC):由spring来完成创建对象,不需要自己的代码中来new对象。
spring获取bean的方法有:
1.通过ClassPathXmlApplicationContext类来创建
在applicationContext.xml配置HelloWorld类
ClassPathXmlApplicationContext cpa=null;
cpa = new ClassPathXmlApplicationContext("applicationContext.xml");
hello=(HelloWorld)cpa.getBean("hello");
hello.sayName("小刚");
2.通过FileSystemResource来创建
注意:这里的相对路径是工程目录,而非classpath
ClassPathResource resource1 = new ClassPathResource("applicationContext.xml"); BeanFactory factory1 = new XmlBeanFactory(resource1); hello=(HelloWorld)factory1.getBean("hello"); hello.sayName("Drive");
3.通过ClassPathResource类来完成:这里的相对路径是classpath:
ClassPathResource resource1 = new ClassPathResource("applicationContext.xml"); BeanFactory factory1 = new XmlBeanFactory(resource1); hello=(HelloWorld)factory1.getBean("hello"); hello.sayName("Drive");
以上三种方法都是通过在xml中配置实现类
4.可以通过注解的方式注入
扫描二维码关注公众号,回复:
506764 查看本文章
5.通过实现ApplicationContextAware方法 :
如果javaBean实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法
@Service @Lazy(false) public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext contex) throws BeansException { context = contex; } public static ApplicationContext getContext() { return context; } }