Spring5依赖注入(DI)拓展(pc命名空间)注入实现收录
命名空间pc注入
User.java
package com.lanyy.pojo;
public class User {
private String name;
private int age;
// 引入无参构造器 确保p命名空间注入
// 引入有参构造器 确保c命名空间注入
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
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 +
'}';
}
}
p与c命名空间注入
p命名空间导入约束 : xmlns:p="http://www.springframework.org/schema/p" <!--P(属性: properties)命名空间 , 属性依然要设置set方法--> c命名空间导入约束 : xmlns:c="http://www.springframework.org/schema/c" <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- <bean id="user" class="com.lanyy.pojo.User">-->
<!-- <property name="name" value="lanyy"/>"-->
<!-- </bean>-->
<!-- p命名空间注入,可以直接注入属性的值:property 无参构造 -->
<bean id="user" class="com.lanyy.pojo.User" p:name="懒羊羊" p:age="18"/>
<!-- c命名空间注入,可以直接注入构造器:constructor-args 有参构造 -->
<bean id="users" class="com.lanyy.pojo.User" c:age="18" c:name="lanyy699"/>
</beans>
Test类编写
@Test
public void test2() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
Object user = context.getBean("user");
System.out.println(user);
}
@Test
public void test3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
Object users = context.getBean("users");
System.out.println(users);
}
测试运行
users = context.getBean("users");
System.out.println(users);
}
了解更多知识请戳下: