Spring set注入

阳光穿透心脏的1/2处 2022-12-17 10:54 232阅读 0赞

通过set方法进行属性的注入

#

一、新建类

首先建一个普通类,定义属性,并生成相应的set方法

Book.java

  1. /**
  2. * set方法进行注入
  3. */
  4. public class Book {
  5. private String bname;
  6. private String bauthor;
  7. public void setBname(String bname) {
  8. this.bname = bname;
  9. }
  10. public void setBauthor(String bauthor) {
  11. this.bauthor = bauthor;
  12. }
  13. public void testDemo(){
  14. System.out.println(bname+" "+bauthor);
  15. }
  16. }

#

二、编写配置文件

在配置文件中配置对象创建并进行属性注入

bean2.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!--1.配置Book对象创建-->
  6. <bean id="book" class="com.health.IOC.B_set注入.Book">
  7. <!--2.set方法注入属性-->
  8. <property name="bname" value="围城"/>
  9. <property name="bauthor" value="钱钟书"/>
  10. </bean>
  11. </beans>

#

三、测试

test02.java

  1. public class test02 {
  2. public static void main(String[] args) {
  3. ApplicationContext context =
  4. new ClassPathXmlApplicationContext("com/health/IOC/B_set注入/bean2.xml");
  5. Book book = context.getBean("book",Book.class);
  6. book.testDemo();
  7. }
  8. }

输出结果:

20201023141758880.png

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring set注入和构造注入的区别

    Spring种提供了2种常用的注入方式,set方法注入和构造函数注入。由于这2种注入方式很相似,都可以满足我们的需求,所以在大多数情况下我们忽视了这2种注入方式的区别。下面让我