c命名空间和p命名空间不能直接使用,需要在bean的xml文件中导入xml约束。
实体类(User)
package com.harris.pojo;
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1.c命名空间注入
c: constructor-arg
构造器注入,类中要写有参构造
xmlns:c="http://www.springframework.org/schema/c"
<bean id="user1" class="com.harris.pojo.User" c:name="Herio" c:age="18"/>
2.p命名空间注入
p: property
要有无参构造。
xmlns:p="http://www.springframework.org/schema/p"
<bean id="user" class="com.harris.pojo.User" p:name="Harris" p:age="19"/>
测试Test类
import com.harris.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void Test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
System.out.println(user.toString());
}
@Test
public void Test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user1",User.class);
System.out.println(user.toString());
}
}
结果