- IOC
- 1.IOC接口
- 2.IOC操作
- 2.1 IOC操作 Bean
- 2.1.1 基于XML方式创建对象
- 2.1.2 :注入依赖DI:基本属性注入
- 1:第一种方法:set方法注入
- 2:第二种方法:P空间注入
- 3:第二种方法:有参构造器注入
- 2.1.3 :注入依赖DI:字面量注入
- 1:空值注入
- 2:特殊符号注入
说明:
FileSystemXmlApplicationContext:路径为盘符路径
ClassPathXmlApplicationContext:路径为文件路径
第一步:创建一个类,设置属性以及对于的set方法
public class Book {
public String auto;
public String name;
public void setAuto(String auto) {
this.auto = auto;
}
public void setName(String name) {
this.name = name;
}
}
第二步:在spring配置文件(.xml文件)中配置对象的创建以及属性的注入
第三步:使用
public class Main {
public static void main(String[] args) {
//1.加载spring配置文件
//FileSystemXmlApplicationContext:路径为盘符路径
//ClassPathXmlApplicationContext:路径为文件路径
ApplicationContext context=
new ClassPathXmlApplicationContext("Test_spring5.xml");
//2.创建对象
Book book=context.getBean("book",Book.class);
System.out.println(book.auto);
}
}
2:第二种方法:P空间注入
这种方法底层还是使用set,但是更简化
第一步:在xml文件中的beans中添加xmlns:p="http://www.springframework.org/schema/p"
第二步:配置bean
第三步:使用
public class Main {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("Test_spring5.xml");
Book fin=context.getBean("book",Book.class);
System.out.println(fin.auto+fin.name);
}
}
3:第二种方法:有参构造器注入
第一步:创建一个类,设置属性以及构造器
public class finance {
public String date;
public String name;
public finance(String date, String name) {
this.date = date;
this.name = name;
}
}
第二步:在xml文件里面配置
或者
第三步:使用
public class Main {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("Test_spring5.xml");
finance fin=context.getBean("finance",finance.class);
System.out.println(fin.date+fin.name);
}
}
2.1.3 :注入依赖DI:字面量注入
1:空值注入
2:特殊符号注入
>]]>



