文章目录
- @[toc]
- 思维导图
- 提要
- 1 spring使用setter注入
- 1.1 注入普通类型数据
- 1.2 注入引用类型数据
- 1.3 获取bean调用方法或获取值
- 2 spring使用构造器注入
- 2.1 在目标类中重写构造方法,将需要引用的对象传入构造方法
- 2.2 注入引用类型数据
- 2.3 在主方法中获取bean调用方法
- 结尾彩蛋
📖博主介绍
个人主页: Zinksl编程社区: Zinksl编程酒馆
个人格言: 想法落实的最佳时机就是现在!🏄
如果你 喜欢交流或热爱分享,欢迎加入编程社区或交流群 大家一起学习技术,交流心得,共同进步🚅
思维导图
提要
配置文件中的标签及属性说明
bean的概念:Spring框架在运行时管理的对象
标签 |
说明 |
子标签 |
属性 |
bean |
配置管理bean的标签 |
property、constructor-arg |
|
property |
setter注入时使用property标签注入内容 |
array、list、set、map |
name, |
constructor-arg |
构造器注入时使用constructor-arg标签注入内容 |
||
array |
注入集合时候使用 |
value |
|
value |
注入集合时候使用用于写值 |
||
1 spring使用setter注入
1.1 注入普通类型数据
(1)在目标类中添加变量设置set方法
(2)在配置文件中,添加property标签
1.2 注入引用类型数据
(1)在目标类中添加变量设置set方法
private BookDao bookDao ;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
(2)在配置文件中,添加property标签
1.3 获取bean调用方法或获取值
public static void main(String[] args) {
// 第一步获取Spring容器
ClassPathXmlApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取bean
BookService bookService = (BookService) act.getBean("bookService");
BookDao bookDao = (BookDao) act.getBean("bookDao");
// 调用方法
bookService.say();
// act.close();
act.registerShutdownHook();
}
}
2 spring使用构造器注入
2.1 在目标类中重写构造方法,将需要引用的对象传入构造方法
// 应用类型数据
private StudentDao studentDao;
// 普通类型数据
private String name;
private int age;
// 重写构造器
public StudentService(StudentDao stu,int ageParameter,String nameParameter) {
this.studentDao = stu;
this.age = ageParameter;
this.name = nameParameter;
}
2.2 注入引用类型数据
在配置文件中的bean标签下新增constructor-arg标签
2.3 在主方法中获取bean调用方法
//第一步获取容器
ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
StudentService studentService = (StudentService) apc.getBean("studentService");
studentService.say();
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net