目录
- 一,什么是Spring IoC容器
- 二,IoC有哪些优点
- 三,控制反转(IoC)有什么作用
- 四,IoC和DI有什么区别⭐
- 五,Spring IoC的实现机制⭐
- 六,IoC支持哪些功能
- 七,BeanFactory和ApplicationContext有什么区别⭐
- 八,ApplicationContext通常的实现是什么
- 九,依赖注入的方式,构造器依赖注入和 Setter方法注入的区别⭐
- 十,依赖注入的基本原则和优点
一,什么是Spring IoC容器
二,IoC有哪些优点
三,控制反转(IoC)有什么作用
public class IocCarExample {
public static void main(String[] args) {
Tire tire = new Tire(20);
Bottom bottom = new Bottom(tire);
Framework framework = new Framework(bottom);
Car car = new Car(framework);
car.run();
}
//车类,把创建⼦类的⽅式,改为注⼊传递的⽅式
static class Car {
private Framework framework;
public Car(Framework framework) {
this.framework = framework;
}
public void run() {
framework.init();
}
}
//车身类
static class Framework {
private Bottom bottom;
public Framework(Bottom bottom) {
this.bottom = bottom;
}
public void init() {
bottom.init();
}
}
四,IoC和DI有什么区别⭐
五,Spring IoC的实现机制⭐
工厂模式案例:
public static void main(String[] arge){
// 调用工厂方法,根据传入参数,返回一个对象
BaseService userService = Factory.getBean("user");
}
class Factory{
public static BaseService getBean(String beanName){
if("user".equals(beanName)){
return = new UserServiceImpl();
}
if("role".equals(beanName)){
return = new RoleServiceImpl();
}
}
}
class Factory {
public static Fruit getInstance(String ClassName) {
Fruit f=null;
try {
f=(Fruit)Class.forName(ClassName).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
【扩展:反射是什么,反射的实现原理】
反射机制是在运行的状态,对于任何一个类,都能知道所有属性和方法,对于任何一个对象都能调用任意方法属性,所以反射就是将Java类的各种成分映射成一个个对象
- ①通过Class类的静态方法:forName(String className)(常用)获取Class对象
try {
Class stuClass3 = Class.forName("fanshe.Student");//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名
System.out.println(stuClass3 == stuClass2);//判断三种方式是否获取的是同一个Class对象
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
- ②通过反射获取构造方法并使用:
public class Student {
//---------------构造方法-------------------
//(默认的构造方法)
Student(String str){
System.out.println("(默认)的构造方法 s = " + str);
}
//无参构造方法
public Student(){
System.out.println("调用了公有、无参构造方法执行了。。。");
}
//有一个参数的构造方法
public Student(char name){
System.out.println("姓名:" + name);
}
//有多个参数的构造方法
public Student(String name ,int age){
System.out.println("姓名:"+name+"年龄:"+ age);//这的执行效率有问题,以后解决。
}
//受保护的构造方法
protected Student(boolean n){
System.out.println("受保护的构造方法 n = " + n);
}
//私有构造方法
private Student(int age){
System.out.println("私有的构造方法 年龄:"+ age);
}
}
六,IoC支持哪些功能
七,BeanFactory和ApplicationContext有什么区别⭐
//先得到Spring上下文
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");//配置文件对应
// 先得到 spring 获取 bean 的对象
BeanFactory beanFactory =
new XmlBeanFactory(new ClassPathResource("spring-config.xml"));