0
点赞
收藏
分享

微信扫一扫

04 Spring依赖注入


文章目录

  • @[toc]
  • 思维导图
  • 提要
  • 1 spring使用setter注入
  • 1.1 注入普通类型数据
  • 1.2 注入引用类型数据
  • 1.3 获取bean调用方法或获取值
  • 2 spring使用构造器注入
  • 2.1 在目标类中重写构造方法,将需要引用的对象传入构造方法
  • 2.2 注入引用类型数据
  • 2.3 在主方法中获取bean调用方法
  • 结尾彩蛋

📖博主介绍

个人主页: Zinksl编程社区: Zinksl编程酒馆
个人格言: 想法落实的最佳时机就是现在!🏄

如果你 喜欢交流热爱分享,欢迎加入编程社区交流群 大家一起学习技术,交流心得,共同进步🚅

思维导图

04 Spring依赖注入_数据

提要

配置文件中的标签及属性说明

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标签

<bean id="bookService" class="com.zinksl.service.impl.BookService">
        <property name="bookDao" value="普通类型数据"/>
</bean>

1.2 注入引用类型数据

(1)在目标类中添加变量设置set方法

private BookDao bookDao ;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

(2)在配置文件中,添加property标签

<bean id="bookService" class="com.zinksl.service.impl.BookService">
        <property name="bookDao" ref="bookDao"/>
</bean>

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标签

<!-- studentDao对象 -->
<bean id="studentDao" class="com.zinksl.dao.impl.StudentDao"/>
<bean id="studentService" class="com.zinksl.service.impl.StudentService">
<!--   此处name指构造器参数名 -->
  <constructor-arg name="stu" ref="studentDao"/>
</bean>

2.3 在主方法中获取bean调用方法

//第一步获取容器
        ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");
		//获取对象
         StudentService studentService = (StudentService) apc.getBean("studentService");
         studentService.say();

举报

相关推荐

0 条评论