博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring系列教程——06参数注入
阅读量:3958 次
发布时间:2019-05-24

本文共 1607 字,大约阅读时间需要 5 分钟。

Spring系列教程——06参数注入

文章目录

一.构造方法讲解

创建一个Student类:

package domain;public class Student {
private String username; private String password; private int age; public Student(String username, String password) {
this.username = username; this.password = password; } public Student(String username, int age) {
this.username = username; this.age = age; } public String getUsername() {
return username; } public void setUsername(String username) {
this.username = username; } public String getPassword() {
return password; } public void setPassword(String password) {
this.password = password; } public int getAge() {
return age; } public void setAge(int age) {
this.age = age; } @Override public String toString() {
return "Student{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; }}

beans.xml文件的配置如下:

注意在写参数时要保证有对应的构造方法否则报错

测试代码为:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");Student student = (Student) context.getBean("student");System.out.println(student);

在这里插入图片描述

另外一种方式时通过索引来配置参数:

表示调用public Student(String username, int age),注意上面的int不可以写成java.lang.Integer,Spring不会自动转化,如果这样写会报错。

二.property标签和p命名空间讲解

关于property标签,其实就是利用setter方法来赋值,这个在前面的章节已经演示过了,这里不做演示。我们来看看p命名空间的参数注入方式。

benas.xml文件配置如下:

运行测试代码如下:

在这里插入图片描述

转载地址:http://ttlzi.baihongyu.com/

你可能感兴趣的文章