• 中文
    • English
  • 注册
  • 查看作者
    • Spring:使用构造方法创建对象

      《Spring:简单使用》一文中,我们配置JavaBean采用的是调用set方法配置的,除了上述方式外,还可以使用构造方法进行配置:

      首先为Book类添加构造方法:

      public Book(Integer bookId, String name, String author, Double price) {
          this.bookId = bookId;
          this.name = name;
          this.author = author;
          this.price = price;
      }

      方法一,在bean标签中,使用constructor-arg标签,其中:

      • name就是Book的构造方法的形参中的参数名

      • value 就是是要传入的实参的值

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
          <bean id="book2" class="io.zhangjia.entity.Book" >
              <constructor-arg name="bookId" value="1" />
              <constructor-arg name="name" value="Spring开发" />
              <constructor-arg name="price" value="19.9" />
              <constructor-arg  name="author" value="张三" />
          </bean>
      
      </beans>

      测试类输出:

      book1 = Book{bookId=2, name='Spring开发', author='张三', price=19.9}

      方法二,去掉name标签,直接写value,Spring会按照构造方法参数的声明顺序来赋值:

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
            <bean id="book3" class="io.zhangjia.entity.Book">
              <constructor-arg value="1"/>
              <constructor-arg value="2"/>
              <constructor-arg value="3"/>
              <constructor-arg value="4"/>
          </bean>
      </beans>

      测试类输出:

      book3 = Book{bookId=1, name='2', author='3', price=4.0}

      方法三,添加index标签,则Spring会根据构造方法的参数声明顺序赋值,比如index  = 0,就是为bookId赋值,index  = 1,就是为name赋值。

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
         
          <bean id="book4" class="io.zhangjia.entity.Book">
              <constructor-arg index="1" value="1"/>
              <constructor-arg index="3" value="2"/>
              <constructor-arg index="2" value="3"/>
              <constructor-arg index="0" value="4"/>
          </bean>
      </beans>

      测试类输出:

      book4 = Book{bookId=4, name='1', author='3', price=2.0}

    • 0
    • 0
    • 0
    • 1.4k
    • 请登录之后再进行评论

      登录

      赞助本站

      • 支付宝
      • 微信
      • QQ

      感谢一直支持本站的所有人!

      单栏布局 侧栏位置: