p命名空间注入
导入p名称空间
xmlns:p="http://www.springframework.org/schema/p"
直接输入p就会有相关的属性弹出
java
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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="user" class="org.example.User" p:name="张三" p:age="20">
</bean>
</beans>
java
package org.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test6 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user=(User) context.getBean("user");
System.out.println(user);
}
}
User user=(User) context.getBean("user");
也可以这么写
User user=context.getBean("user",User.class);
c命名空间注入
xmlns:c="http://www.springframework.org/schema/c"
需要添加一个有参构造函数
通过构造器注入
java
<bean id="user" class="org.example.User" c:name="张三" c:age="20">
</bean>
java
public class Test6 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user= context.getBean("user",User.class);
System.out.println(user);
}
}