04 Spring依赖注入

📖博主介绍


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

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


思维导图


提要

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

bean的概念:Spring框架在运行时管理的对象

标签说明子标签属性
bean配置管理bean的标签property、constructor-arg
propertysetter注入时使用property标签注入内容array、list、set、mapname,
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();

结尾彩蛋

认真分享技术,记录学习点滴若内容对你有用可以鼓励一下🍻方式如下
点赞:👍 留言:✍收藏:⭐️

如有疑问欢迎评论区留言,或加入技术交流群:1002743802
关注我订阅专栏,会持续体系化更新哦👈

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zinksl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值