1.loc思想
-
传统获取资源的方式
自己做饭:要洗菜,烧火,炒菜,煮饭等自己全过程参入工作,非常吃力,你必须熟练的掌握做饭的全部过程和每一个细节
在应用程序中的组件需要获取资源时,传统的方式是组件主动从容器中获取所需要的资源,这样的开发模式下开发人员往往需要知道在具体容器中特定获取资源的方式,增加学习成本,降低开发效率
-
反转控制方式获取资源
点外卖:下单,等,吃,省时省力,不用关心饭是怎么做的,怎么送到你这里来的
反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源获取方向--改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器时如何创建对象的,只需要提供接受资源的方式即可,极大的降低了学习成本
提高了开发效率
2.入门案例
第一步:创建HelloWorld类
package com.atguigu.spring.pojo;
public class HelloWorld {
public void sayHello(){
System.out.println("spring hello");
}
}
第二步:建立一个xml文件
第三步:配置bean
<bean id="helloworld" class="com.atguigu.spring.pojo.HelloWorld">
</bean>
也可以用快捷键Alt+Insert
说明:这个id是唯一标识,唯一两个字表明不能在有第二个,class是这个id的类型就是你这个类的全类名,带包名的
第四步:测试
package com.atguigu.spring;
import com.atguigu.spring.pojo.HelloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldText {
public static void main(String[] args) {
/*
* 这个ApplicationContext为接口,ClassPathXmlApplicationContext为实现类
* getBean有三个获取方式,一个是根据id唯一标识,一个是根据类型,还有一个就是id加类型
* 方式一:id:getBean("helloworld")
* 方式二:class:getBean(HelloWorld.class)
* 方式san:
* */
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) ac.getBean("helloworld");
//HelloWorld helloWorld = ac.getBean(HelloWorld.class);
//HelloWorld helloWorld = ac.getBean("helloworld", HelloWorld.class);
helloWorld.sayHello();
}
}
3.三中获取方式用法
1.根据类型
如果你的类型不是唯一的,有两个同类型bean,如com.atguigu.spring.pojo.HelloWorld类型
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloworld" class="com.atguigu.spring.pojo.HelloWorld">
</bean>
<bean id="helloworld2" class="com.atguigu.spring.pojo.HelloWorld">
</bean>
</beans>
这里有两个同类型bean
如果根据类型获取,他不知道获取哪一个,就会包异常
2.根据id
如果id一样,类型不同也会报错
3.根据id和类型最为保险