新建JavaBean对象Person(int id,String name,String sex,int age ,List favor),通过spring框架给person对象完成值的注入(分别用构造注入和set注入完成),创建测试类,打印输出person的值。
时间: 2023-03-15 16:00:37 浏览: 110
使用构造注入,可以创建一个带有参数的构造函数,将所有参数传入构造函数,然后在构造函数中将参数赋值给实例变量:public Person(int id,String name,String sex,int age,List favor) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.favor = favor;
}使用set注入,可以创建一个没有参数的构造函数,然后在外部通过set方法将属性设置进去:public Person() {}public void setId(int id) {
this.id = id;
}public void setName(String name) {
this.name = name;
}public void setSex(String sex) {
this.sex = sex;
}public void setAge(int age) {
this.age = age;
}public void setFavor(List favor) {
this.favor = favor;
}创建测试类,可以通过实例化Person类,然后调用get方法来打印输出person的值:public class Test {
public static void main(String[] args) {
Person person = new Person(1, "张三", "男", 18, Arrays.asList("篮球", "足球"));
System.out.println("id:" + person.getId());
System.out.println("name:" + person.getName());
System.out.println("sex:" + person.getSex());
System.out.println("age:" + person.getAge());
System.out.println("favor:" + person.getFavor());
}
}
阅读全文